forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0494-target-sum.ts
62 lines (51 loc) · 1.69 KB
/
0494-target-sum.ts
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
function findTargetSumWays(nums: number[], target: number): number {
// key: index, sum till index element, value: number of ways to get to that sum
const cache = new Map();
const backTrack = (i, sum) => {
/* if we're at the last element + 1 we compare the sum to our target
if it's true, we've found a way to our sum!
*/
if (i === nums.length) {
if (sum === target) {
return 1;
}
return 0;
}
// if already index, sum pair exist in our HashMap, we return the memoized result
if (cache.has(`${i},${sum}`)) {
return cache.get(`${i},${sum}`);
}
// DP: we memoize number of ways of each pair index, sum
cache.set(
`${i},${sum}`,
backTrack(i + 1, sum + nums[i]) + backTrack(i + 1, sum - nums[i])
);
return cache.get(`${i},${sum}`);
};
return backTrack(0, 0);
}
/**
* DP - Bottom Up
* Time O(N * M) | Space O(M)
* https://leetcode.com/problems/target-sum/
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
function findTargetSumWays(nums: number[], target: number): number {
const total = nums.reduce((a, b) => a + b);
const m = total * 2 + 1;
let dp = new Array(m).fill(0);
dp[total] = 1; // base case
for (let i = 0; i < nums.length; i++) {
const current = new Array(m);
const num = nums[i];
for (let j = 0; j < current.length; j++) {
const left = dp[j - num] ?? 0;
const right = dp[j + num] ?? 0;
current[j] = left + right;
}
dp = current;
}
return dp[total + target] ?? 0;
};