Skip to content

Commit b6286f7

Browse files
authored
Create Target Sum.java
1 parent c271ea2 commit b6286f7

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Medium/Target Sum.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
int count;
3+
public int findTargetSumWays(int[] nums, int S) {
4+
int[][] dp = new int[nums.length][2001];
5+
for (int[] row : dp) {
6+
Arrays.fill(row, Integer.MIN_VALUE);
7+
}
8+
return calculateWays(nums, 0, 0, S, dp);
9+
}
10+
11+
private void calculateWaysDfs(int[] nums, int idx, int S) {
12+
if (idx == nums.length) {
13+
if (S == 0) {
14+
count++;
15+
}
16+
return;
17+
}
18+
dfs(nums, idx + 1, S - nums[idx]);
19+
dfs(nums, idx + 1, S + nums[idx]);
20+
}
21+
22+
private int calculateWaysDp(int[] nums, int idx, int sum, int S, int[][] dp) {
23+
if (idx == nums.length) {
24+
return sum == S ? 1 : 0;
25+
}
26+
if (dp[idx][sum + 1000] != Integer.MIN_VALUE) {
27+
return dp[idx][sum + 1000];
28+
}
29+
int add = calculateWaysDp(nums, idx + 1, sum + nums[idx], S, dp);
30+
int sub = calculateWaysDp(nums, idx + 1, sum - nums[idx], S, dp);
31+
dp[idx][sum + 1000] = add + sub;
32+
return dp[idx][sum + 1000];
33+
}
34+
}

0 commit comments

Comments
 (0)