Skip to content

Commit 7db705c

Browse files
authored
Update 494-target-sum.js
1 parent 94a7a97 commit 7db705c

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

494-target-sum.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,36 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number}
5+
*/
6+
const findTargetSumWays = function(nums, target) {
7+
const sum = nums.reduce((a, b) => a+b);
8+
9+
if(Math.abs(target) > sum) {
10+
return 0;
11+
}
12+
13+
if((target + sum) % 2) {
14+
return 0;
15+
}
16+
17+
const halfSum = (target + sum) / 2;
18+
19+
let dp = new Array(halfSum+1).fill(0);
20+
dp[0] = 1;
21+
22+
for(let i = 0; i < nums.length; i++) {
23+
for(let j = halfSum; j >= nums[i]; j--) {
24+
dp[j] += dp[j - nums[i]];
25+
}
26+
}
27+
28+
return dp[halfSum];
29+
};
30+
31+
32+
// another
33+
134
/**
235
* @param {number[]} nums
336
* @param {number} S

0 commit comments

Comments
 (0)