mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #468 from jackeyjia/patch-2
add js solution for findTargetSumWays
This commit is contained in:
@ -306,6 +306,36 @@ func findTargetSumWays(nums []int, target int) int {
|
||||
}
|
||||
```
|
||||
|
||||
Javascript:
|
||||
```javascript
|
||||
const findTargetSumWays = (nums, target) => {
|
||||
|
||||
const sum = nums.reduce((a, b) => a+b);
|
||||
|
||||
if(target > sum) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if((target + sum) % 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const halfSum = (target + sum) / 2;
|
||||
nums.sort((a, b) => a - b);
|
||||
|
||||
let dp = new Array(halfSum+1).fill(0);
|
||||
dp[0] = 1;
|
||||
|
||||
for(let i = 0; i < nums.length; i++) {
|
||||
for(let j = halfSum; j >= nums[i]; j--) {
|
||||
dp[j] += dp[j - nums[i]];
|
||||
}
|
||||
}
|
||||
|
||||
return dp[halfSum];
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user