-
Notifications
You must be signed in to change notification settings - Fork 0
/
target-sum.js
40 lines (35 loc) · 937 Bytes
/
target-sum.js
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
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var findTargetSumWays = function(nums, target) {
var sum = 0;
nums.forEach(function(num){
sum += num;
});
if(target>sum || target<-sum)
return 0;
var dp = [];
dp[0+sum] = 1;
var maxIndex = sum*2+1;
nums.forEach(function(num){
var tmp = [];
for(var k=0;k<maxIndex;k++){
if(dp[k] !== undefined && dp[k] !== 0){
if(tmp[k+num] === undefined){
tmp[k+num] = dp[k];
}else{
tmp[k+num] += dp[k];
}
if(tmp[k-num] === undefined){
tmp[k-num] = dp[k];
}else{
tmp[k-num] += dp[k];
}
}
}
dp = tmp;
});
return dp[target+sum]===undefined?0:dp[target+sum];
};