|
1 | 1 | class Solution {
|
2 | 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, new HashMap<>()); |
| 3 | + Map<String, Integer> memo = new HashMap<>(); |
| 4 | + return helper(nums, S, 0, memo); |
8 | 5 | }
|
9 | 6 |
|
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; |
14 | 10 | }
|
15 | 11 |
|
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); |
21 | 16 | }
|
22 | 17 |
|
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); |
25 | 22 |
|
26 |
| - m.put(encodedVal, add + minus); |
27 |
| - return add + minus; |
| 23 | + memo.put(key, result); |
| 24 | + return result; |
28 | 25 | }
|
29 | 26 | }
|
0 commit comments