Skip to content

Commit 137451c

Browse files
committed
Update 0494-target-sum.ts
1 parent b90e783 commit 137451c

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

typescript/0494-target-sum.ts

+31
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,34 @@ function findTargetSumWays(nums: number[], target: number): number {
2929

3030
return backTrack(0, 0);
3131
}
32+
33+
34+
/**
35+
* DP - Bottom Up
36+
* Time O(N * M) | Space O(M)
37+
* https://leetcode.com/problems/target-sum/
38+
* @param {number[]} nums
39+
* @param {number} target
40+
* @return {number}
41+
*/
42+
function findTargetSumWays(nums: number[], target: number): number {
43+
const total = nums.reduce((a, b) => a + b);
44+
const m = total * 2 + 1;
45+
let dp = new Array(m).fill(0);
46+
dp[total] = 1; // base case
47+
48+
for (let i = 0; i < nums.length; i++) {
49+
const current = new Array(m);
50+
const num = nums[i];
51+
52+
for (let j = 0; j < current.length; j++) {
53+
const left = dp[j - num] ?? 0;
54+
const right = dp[j + num] ?? 0;
55+
56+
current[j] = left + right;
57+
}
58+
dp = current;
59+
}
60+
61+
return dp[total + target] ?? 0;
62+
};

0 commit comments

Comments
 (0)