1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution {
int target, n; int[] nums; Map<String, Integer> cache;
public int findTargetSumWays(int[] nums, int target) { this.nums = nums; this.n = nums.length; this.target = target; cache = new HashMap<>(); return dfs(0, 0); }
private int dfs(int index, int sum) { String key = index + "_" + sum; if (cache.containsKey(key)) return cache.get(key); if (index == n) { cache.put(key, sum == target ? 1 : 0); return cache.get(key); } else { int left = dfs(index + 1, sum + nums[index]); int right = dfs(index + 1, sum - nums[index]); cache.put(key, left + right); return cache.get(key); } } }
|