-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.js
More file actions
37 lines (30 loc) · 721 Bytes
/
Copy pathsolution.js
File metadata and controls
37 lines (30 loc) · 721 Bytes
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
class Solution {
/**
* @param number[] arr
* @param number target
* @returns number
*/
totalWays(arr, target) {
let totalSum = 0;
for (let num of arr) {
totalSum += num;
}
// If target cannot be formed
if (Math.abs(target) > totalSum) {
return 0;
}
// totalSum + target must be even
if ((totalSum + target) % 2 !== 0) {
return 0;
}
let required = Math.floor((totalSum + target) / 2);
let dp = new Array(required + 1).fill(0);
dp[0] = 1;
for (let num of arr) {
for (let sum = required; sum >= num; sum--) {
dp[sum] += dp[sum - num];
}
}
return dp[required];
}
}