-
Notifications
You must be signed in to change notification settings - Fork 414
Expand file tree
/
Copy pathcode.js
More file actions
29 lines (24 loc) · 731 Bytes
/
code.js
File metadata and controls
29 lines (24 loc) · 731 Bytes
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
29
/** Recursion, memoization
* https://leetcode.com/problems/target-sum/
*
* Time O(m*n) where n = nums.length and m = target;
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var findTargetSumWays = function(nums, target) {
const cache = new Map();
function dfs(i, total) {
const key = i + "-" + total;
if(cache.has(key)) return cache.get(key);
if(i === nums.length) {
if(total === target) return 1;
return 0;
}
const result = (dfs(i + 1, total + nums[i]) + dfs(i + 1, total - nums[i]));
cache.set(key, result);
return cache.get(key);
// return cache[i+"-"+total];
}
return dfs(0,0);
};