-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0494-target-sum.js
More file actions
31 lines (23 loc) · 1.01 KB
/
0494-target-sum.js
File metadata and controls
31 lines (23 loc) · 1.01 KB
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
/**
* Target Sum
* Time Complexity: O(N * S)
* Space Complexity: O(N * S)
*/
var findTargetSumWays = function (nums, target) {
const memoizationStore = new Map();
function computeCombinations(currentNumberIndex, currentAccumulatedSum) {
if (currentNumberIndex === nums.length) {
return currentAccumulatedSum === target ? 1 : 0;
}
const stateKey = `${currentNumberIndex},${currentAccumulatedSum}`;
if (memoizationStore.has(stateKey)) {
return memoizationStore.get(stateKey);
}
const resultFromAddition = computeCombinations(currentNumberIndex + 1, currentAccumulatedSum + nums[currentNumberIndex]);
const resultFromSubtraction = computeCombinations(currentNumberIndex + 1, currentAccumulatedSum - nums[currentNumberIndex]);
const totalPossibleWays = resultFromAddition + resultFromSubtraction;
memoizationStore.set(stateKey, totalPossibleWays);
return totalPossibleWays;
}
return computeCombinations(0, 0);
};