Skip to content

Commit 69a5afd

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 494_Target_Sum.java
1 parent 144bf98 commit 69a5afd

File tree

1 file changed

+15
-18
lines changed

1 file changed

+15
-18
lines changed
Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,26 @@
11
class Solution {
22
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, new HashMap<>());
3+
Map<String, Integer> memo = new HashMap<>();
4+
return helper(nums, S, 0, memo);
85
}
96

10-
private int dfs(int[] nums, int S, int sum, int idx, Map<String, Integer> m) {
11-
String encodedVal = idx + "->" + sum;
12-
if (m.containsKey(encodedVal)) {
13-
return m.get(encodedVal);
7+
private int helper(int[] nums, int sum, int idx, Map<String, Integer> memo) {
8+
if (idx == nums.length) {
9+
return sum == 0 ? 1 : 0;
1410
}
1511

16-
if (idx == nums.length) {
17-
if (sum == S) {
18-
return 1;
19-
}
20-
return 0;
12+
String key = idx + "," + sum;
13+
14+
if (memo.containsKey(key)) {
15+
return memo.get(key);
2116
}
2217

23-
int add = dfs(nums, S, sum + nums[idx], idx + 1, m);
24-
int minus = dfs(nums, S, sum - nums[idx], idx + 1, m);
18+
int result = 0;
19+
20+
result += helper(nums, sum + nums[idx], idx + 1, memo);
21+
result += helper(nums, sum - nums[idx], idx + 1, memo);
2522

26-
m.put(encodedVal, add + minus);
27-
return add + minus;
23+
memo.put(key, result);
24+
return result;
2825
}
2926
}

0 commit comments

Comments
 (0)