forked from tangweikun/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
44 lines (39 loc) · 982 Bytes
/
index.ts
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
41
42
43
44
// export const findTargetSumWays = (nums: number[], target: number): any => {
// if (nums.length === 1) {
// if (nums[0] === 0 && target === 0) return 2
// if (nums[0] === Math.abs(target)) return 1
// return 0
// }
// return (
// findTargetSumWays(
// nums.slice(0, nums.length - 1),
// target + nums[nums.length - 1],
// ) +
// findTargetSumWays(
// nums.slice(0, nums.length - 1),
// target - nums[nums.length - 1],
// )
// )
// }
// HELP:
export const findTargetSumWays = (nums: number[], S: number): any => {
let sum = 0
for (let i = 0; i < nums.length; i++) {
sum += nums[i]
}
if (sum < S || (sum + S) % 2 !== 0) {
return 0
}
const target = (S + sum) / 2
const dp = []
for (let i = 0; i <= target; i++) {
dp[i] = 0
}
dp[0] = 1
for (let i = 0; i < nums.length; i++) {
for (let j = target; j >= nums[i]; j--) {
dp[j] += dp[j - nums[i]]
}
}
return dp[target]
}