|
| 1 | +/** |
| 2 | + * Subset Sum Problem |
| 3 | + * |
| 4 | + * Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum. |
| 5 | + * |
| 6 | + * Examples: set[] = {3, 34, 4, 12, 5, 2}, sum = 9 |
| 7 | + * Output: True //There is a subset (4, 5) with sum 9. |
| 8 | + */ |
| 9 | + |
| 10 | +/** |
| 11 | + * Recursion |
| 12 | + * |
| 13 | + * Returns true if there is a subset of set[] with sum equal to given sum |
| 14 | + * |
| 15 | + * @param {number[]} set |
| 16 | + * @param {number} n |
| 17 | + * @param {number} sum |
| 18 | + * @return {boolean} |
| 19 | + */ |
| 20 | +const isSubsetSumR = (set, n, sum) => { |
| 21 | + // Base Cases |
| 22 | + if (sum === 0) { |
| 23 | + return true; |
| 24 | + } |
| 25 | + |
| 26 | + if (n === 0 && sum !== 0) { |
| 27 | + return false; |
| 28 | + } |
| 29 | + |
| 30 | + // If last element is greater than |
| 31 | + // sum, then ignore it |
| 32 | + if (set[n - 1] > sum) { |
| 33 | + return isSubsetSumR(set, n - 1, sum); |
| 34 | + } |
| 35 | + |
| 36 | + // else, check if sum can be obtained by any of the following |
| 37 | + // (a) including the last element |
| 38 | + // (b) excluding the last element |
| 39 | + return isSubsetSumR(set, n - 1, sum) || isSubsetSumR(set, n - 1, sum - set[n - 1]); |
| 40 | +}; |
| 41 | + |
| 42 | +/** |
| 43 | + * Dynamic Programming |
| 44 | + * |
| 45 | + * Returns true if there is a subset of set[] with sum equal to given sum |
| 46 | + * |
| 47 | + * @param {number[]} set |
| 48 | + * @param {number} n |
| 49 | + * @param {number} sum |
| 50 | + * @return {boolean} |
| 51 | + */ |
| 52 | +const isSubsetSum = (set, n, sum) => { |
| 53 | + // The value of subset[i][j] will be true if there is a subset of |
| 54 | + // set[0..j-1] with sum equal to i |
| 55 | + const dp = Array(sum + 1) |
| 56 | + .fill() |
| 57 | + .map(() => Array(n + 1)); |
| 58 | + |
| 59 | + // If sum is 0, then answer is true |
| 60 | + for (let i = 0; i <= n; i++) { |
| 61 | + dp[0][i] = true; |
| 62 | + } |
| 63 | + |
| 64 | + // If sum is not 0 and set is empty, |
| 65 | + // then answer is false |
| 66 | + for (let i = 1; i <= sum; i++) { |
| 67 | + dp[i][0] = false; |
| 68 | + } |
| 69 | + |
| 70 | + // Fill the subset table in botton up manner |
| 71 | + for (let i = 1; i <= sum; i++) { |
| 72 | + for (let j = 1; j <= n; j++) { |
| 73 | + dp[i][j] = dp[i][j - 1]; |
| 74 | + |
| 75 | + if (i >= set[j - 1]) { |
| 76 | + dp[i][j] = dp[i][j] || dp[i - set[j - 1]][j - 1]; |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + return dp[sum][n]; |
| 82 | +}; |
0 commit comments