Skip to content

Commit d851d4d

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 494_Target_Sum.java
1 parent e2fce0a commit d851d4d

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public int findTargetSumWays(int[] nums, int S) {
3+
if (nums == null || nums.length == 0) {
4+
return 0;
5+
}
6+
7+
return dfs(nums, S, 0, 0);
8+
}
9+
10+
private int dfs(int[] nums, int S, int sum, int idx) {
11+
if (idx == nums.length) {
12+
if (sum == S) {
13+
return 1;
14+
}
15+
return 0;
16+
}
17+
18+
int add = dfs(nums, S, sum + nums[idx], idx + 1);
19+
int minus = dfs(nums, S, sum - nums[idx], idx + 1);
20+
21+
return add + minus;
22+
}
23+
}

0 commit comments

Comments
 (0)