Skip to content

Commit 735f173

Browse files
authored
Number of Subset equal to given sum (TheAlgorithms#174)
* Number of Subset equal to given sum * Update and rename Number of Subset equal to given sum to NumberOfSubsetEqualToGivenSum.js * Update NumberOfSubsetEqualToGivenSum.js
1 parent 9000e1c commit 735f173

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
Given an array of non-negative integers and a value sum,
3+
determine the total number of the subset with sum
4+
equal to the given sum.
5+
*/
6+
/*
7+
Given solution is O(n*sum) Time complexity and O(sum) Space complexity
8+
*/
9+
function NumberOfSubsetSum (array, sum) {
10+
const dp = [] // create an dp array where dp[i] denote number of subset with sum equal to i
11+
for (let i = 1; i <= sum; i++) {
12+
dp[i] = 0
13+
}
14+
dp[0] = 1 // since sum equal to 0 is always possible with no element in subset
15+
16+
for (let i = 0; i < array.length; i++) {
17+
for (let j = sum; j >= array[i]; j--) {
18+
if (j - array[i] >= 0) {
19+
dp[j] += dp[j - array[i]]
20+
}
21+
}
22+
}
23+
return dp[sum]
24+
}
25+
26+
function main () {
27+
const array = [1, 1, 2, 2, 3, 1, 1]
28+
const sum = 4
29+
const result = NumberOfSubsetSum(array, sum)
30+
console.log(result)
31+
}
32+
main()

0 commit comments

Comments
 (0)