Skip to content

Commit c6f9405

Browse files
authored
Create 0494-target-sum.c
1 parent be373c1 commit c6f9405

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

c/0494-target-sum.c

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
int findTargetSumWays(int* nums, int numsSize, int target) {
2+
int sum = 0;
3+
for (int i = 0; i < numsSize; i++) {
4+
sum += nums[i];
5+
}
6+
if (target > sum || target < -sum) {
7+
return 0;
8+
}
9+
10+
int n = numsSize;
11+
int dp[n + 1][2 * sum + 1];
12+
for (int i = 0; i <= n; i++) {
13+
for (int j = 0; j <= 2 * sum; j++) {
14+
dp[i][j] = 0;
15+
}
16+
}
17+
dp[0][sum] = 1;
18+
19+
for (int i = 0; i < n; i++) {
20+
for (int j = nums[i]; j <= 2 * sum - nums[i]; j++) {
21+
if (dp[i][j]) {
22+
dp[i + 1][j + nums[i]] += dp[i][j];
23+
dp[i + 1][j - nums[i]] += dp[i][j];
24+
}
25+
}
26+
}
27+
28+
return dp[n][sum + target];
29+
}

0 commit comments

Comments
 (0)