mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-19 01:55:51 +08:00

* chore: Switch to Node 20 + Vitest * chore: migrate to vitest mock functions * chore: code style (switch to prettier) * test: re-enable long-running test Seems the switch to Node 20 and Vitest has vastly improved the code's and / or the test's runtime! see #1193 * chore: code style * chore: fix failing tests * Updated Documentation in README.md * Update contribution guidelines to state usage of Prettier * fix: set prettier printWidth back to 80 * chore: apply updated code style automatically * fix: set prettier line endings to lf again * chore: apply updated code style automatically --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
33 lines
821 B
JavaScript
33 lines
821 B
JavaScript
/*
|
|
Given an array of non-negative 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
|
|
*/
|
|
function NumberOfSubsetSum(array, sum) {
|
|
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
|
|
}
|
|
dp[0] = 1 // since sum equal to 0 is always possible with no element in subset
|
|
|
|
for (let i = 0; i < array.length; i++) {
|
|
for (let j = sum; j >= array[i]; j--) {
|
|
if (j - array[i] >= 0) {
|
|
dp[j] += dp[j - array[i]]
|
|
}
|
|
}
|
|
}
|
|
return dp[sum]
|
|
}
|
|
|
|
// example
|
|
|
|
// const array = [1, 1, 2, 2, 3, 1, 1]
|
|
// const sum = 4
|
|
// const result = NumberOfSubsetSum(array, sum)
|
|
|
|
export { NumberOfSubsetSum }
|