Solved·28 Sept
Find K-Sum Subsets
DifficultyMedium
PatternSubsets
TrackDSA
tl;dr
Return all subset with whose sum is k
full write-up
Subsets Summing to K
Problem Statement
Given a set of n positive integers, find all possible subsets of these integers that sum up to a target number, k.
Constraints
1 ≤ n ≤ 101 ≤ x ≤ 100, wherexis any member of the input set1 ≤ k ≤ 10³
Examples
Note: No examples were shared for this problem. Feel free to send them so they can be added here.
Solution
This solution uses the same bitmasking technique used for generating all subsets of a set (the power set), but adds a check to only keep the subsets whose numbers add up to k.
Steps
- If the input set has
nnumbers, there are2ⁿpossible subsets in total. Each subset can be represented by a number from0to2ⁿ - 1, written in binary. Each bit in this number tells us whether to include the number at that position. - We loop through every number
ifrom0to2ⁿ - 1. Each one represents one possible subset. - For each
i, we check every bit positionj(from0toarr.length - 1), using a helper function,getBit(num, bit):- This function shifts
1to the left bybitpositions, then checks if that bit is set (equal to1) innum, using a bitwise AND operation. - If the bit is set, it means the number at that position should be included in this subset.
- This function shifts
- As we build each subset, we also keep a running
sumof its values. - Once we've checked all the bit positions for a given
i, we compare the subset'ssumto our target,k. If they match, we add this subset to our results. - After going through every possible subset, we return the full list of subsets whose sum equals
k.
Code
class Solution {
countSubset(arr, k) {
function getBit(num, bit) {
let mask = 1 << bit;
return (num & mask) !== 0;
}
let result = [];
let subsetsCount = 2 ** arr.length;
for (let i = 0; i < subsetsCount; i++) {
let subset = [];
let sum = 0;
for (let j = 0; j < arr.length; j++) {
if (getBit(i, j)) {
subset.push(arr[j]);
sum += arr[j];
}
}
if (sum === k) {
result.push(subset);
}
}
return result;
}
}