forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumberOfSubsetEqualToGivenSum.js
More file actions
Latest commit
33 lines (30 loc) · 892 Bytes
/
Copy pathNumberOfSubsetEqualToGivenSum.js
File metadata and controls
33 lines (30 loc) · 892 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
/*
Given an array of positive integers and a value sum,
determine the total number of the subset with sum
equal to the given sum.
*/
/*
Given solution is O(n*sum) Time complexity and O(sum) Space complexity
*/
functionNumberOfSubsetSum(array,sum){
if(sum<0){
thrownewError('The sum must be non-negative.')
}
if(!array.every((num)=>num>0)){
thrownewError('All of the inputs of the array must be positive.')
}
constdp=[]// create an dp array where dp[i] denote number of subset with sum equal to i
for(leti=1;i<=sum;i++){
dp[i]=0
}
dp[0]=1// since sum equal to 0 is always possible with no element in subset
for(leti=0;i<array.length;i++){
for(letj=sum;j>=array[i];j--){
if(j-array[i]>=0){
dp[j]+=dp[j-array[i]]
}
}
}
returndp[sum]
}
export{NumberOfSubsetSum}