mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-07 19:17:33 +08:00
test: add tests for NumberOfSubsetEqualToGivenSum
(#1661)
This commit is contained in:
@ -1,5 +1,5 @@
|
||||
/*
|
||||
Given an array of non-negative integers and a value sum,
|
||||
Given an array of positive integers and a value sum,
|
||||
determine the total number of the subset with sum
|
||||
equal to the given sum.
|
||||
*/
|
||||
@ -7,6 +7,13 @@ equal to the given sum.
|
||||
Given solution is O(n*sum) Time complexity and O(sum) Space complexity
|
||||
*/
|
||||
function NumberOfSubsetSum(array, sum) {
|
||||
if (sum < 0) {
|
||||
throw new Error('The sum must be non-negative.')
|
||||
}
|
||||
|
||||
if (!array.every((num) => num > 0)) {
|
||||
throw new Error('All of the inputs of the array must be positive.')
|
||||
}
|
||||
const dp = [] // create an dp array where dp[i] denote number of subset with sum equal to i
|
||||
for (let i = 1; i <= sum; i++) {
|
||||
dp[i] = 0
|
||||
@ -23,10 +30,4 @@ function NumberOfSubsetSum(array, sum) {
|
||||
return dp[sum]
|
||||
}
|
||||
|
||||
// example
|
||||
|
||||
// const array = [1, 1, 2, 2, 3, 1, 1]
|
||||
// const sum = 4
|
||||
// const result = NumberOfSubsetSum(array, sum)
|
||||
|
||||
export { NumberOfSubsetSum }
|
||||
|
Reference in New Issue
Block a user