Count Subset Sum
Input: [1, 1, 2, 3], S=4
Output: 3
The given set has '3' subsets whose sum is '4': {1, 1, 2}, {1, 3}, {1, 3}
Note that we have two similar sets {1, 3}, because we have two '1' in our input.Input: {1, 2, 7, 1, 5}, S=9
Output: 3
The given set has '3' subsets whose sum is '9': {2, 7}, {1, 7, 1}, {1, 2, 1, 5}Solution
let canPartition = function (num, sum) {
const n = num.length;
const dp = Array(n)
.fill(false)
.map(() => Array(sum + 1).fill(false));
// populate the sum=0 column, as we can always have '0' sum without including any element
for (let i = 0; i < n; i++) dp[i][0] = true;
// with only one number, we can form a subset only when the required sum is equal to its value
for (let s = 1; s <= sum; s++) {
dp[0][s] = num[0] == s;
}
// process all subsets for all sums
for (let i = 1; i < n; i++) {
for (let s = 1; s <= sum; s++) {
// if we can get the sum 's' without the number at index 'i'
if (dp[i - 1][s]) {
dp[i][s] = dp[i - 1][s];
} else if (s >= num[i]) {
// else if we can find a subset to get the remaining sum
dp[i][s] = dp[i - 1][s - num[i]];
}
}
}
// the bottom-right corner will have our answer.
return dp[n - 1][sum];
};



Space Optimization
Last updated