|
| 1 | +/* |
| 2 | + * |
| 3 | + * Sum of Subset problem |
| 4 | + * |
| 5 | + * Given an ordered set W of non-negative integers and a value K, |
| 6 | + * determine all possible subsets from the given set W whose sum |
| 7 | + * of its elemets equals to the given value K. |
| 8 | + * |
| 9 | + * More info: https://www.geeksforgeeks.org/subset-sum-backtracking-4/ |
| 10 | + */ |
| 11 | + |
| 12 | +/* |
| 13 | + * @param {number[]} set Original set of numbers |
| 14 | + * @param {number[]} subset Subset being evaluated |
| 15 | + * @param {number} setIndex Index from set of last element in subset |
| 16 | + * @param {number} Sum of elements from subset |
| 17 | + * @param {targetSum} The target sum on which the subset sum is compared to |
| 18 | + * @returns {number[][]} Subsets whose elements add up to targetSum |
| 19 | + */ |
| 20 | +const sumOfSubset = (set, subset, setindex, sum, targetSum) => { |
| 21 | + // Base case where the subset sum is equal to target sum |
| 22 | + // Evaluation of following subsets on this path will always add up to |
| 23 | + // greater than targetSum, so no need to continue |
| 24 | + if (sum === targetSum) return [subset] |
| 25 | + |
| 26 | + // This and following subsets on this path will always add up to |
| 27 | + // greater than targetSum, so no need to continue |
| 28 | + if (sum > targetSum) return [] |
| 29 | + |
| 30 | + // Initialize results array. Will contain only valid subsets |
| 31 | + let results = [] |
| 32 | + |
| 33 | + // Slice gets from the set all the elements at the right of the last element |
| 34 | + // to be evaluated (last element of subset) |
| 35 | + // forEach iterated on the resulting array |
| 36 | + set.slice(setindex).forEach((num, index) => { |
| 37 | + // The next subset to be evaluated, current subset plus next element |
| 38 | + const nextSubset = [...subset, num] |
| 39 | + |
| 40 | + // Next index from the set. Current set index plus iteration index |
| 41 | + // index starts at 0, so a + 1 is required |
| 42 | + const nextSetIndex = setindex + index + 1 |
| 43 | + |
| 44 | + // Sum of elements from the next subset to be evaluated |
| 45 | + const nextSum = sum + num |
| 46 | + |
| 47 | + // Call recursively the sumOfSubset for the nextSubset |
| 48 | + const subsetResult = sumOfSubset( |
| 49 | + set, |
| 50 | + nextSubset, |
| 51 | + nextSetIndex, |
| 52 | + nextSum, |
| 53 | + targetSum |
| 54 | + ) |
| 55 | + |
| 56 | + // Concat the recursive result with current result arary |
| 57 | + results = [...results, ...subsetResult] |
| 58 | + }) |
| 59 | + |
| 60 | + // Return results |
| 61 | + return results |
| 62 | +} |
| 63 | + |
| 64 | +export { sumOfSubset } |
0 commit comments