/** * @param {*[]} originalSet - Original set of elements we're forming power-set of. * @param {*[][]} allSubsets - All subsets that have been formed so far. * @param {*[]} currentSubSet - Current subset that we're forming at the moment. * @param {number} startAt - The position of in original set we're starting to form current subset. * @return {*[][]} - All subsets of original set. */ function btPowerSetRecursive(originalSet, allSubsets = [[]], currentSubSet = [], startAt = 0) { // Let's iterate over originalSet elements that may be added to the subset // without having duplicates. The value of startAt prevents adding the duplicates. for (let position = startAt; position < originalSet.length; position += 1) { // Let's push current element to the subset currentSubSet.push(originalSet[position]); // Current subset is already valid so let's memorize it. // We do array destruction here to save the clone of the currentSubSet. // We need to save a clone since the original currentSubSet is going to be // mutated in further recursive calls. allSubsets.push([...currentSubSet]); // Let's try to generate all other subsets for the current subset. // We're increasing the position by one to avoid duplicates in subset. btPowerSetRecursive(originalSet, allSubsets, currentSubSet, position + 1); // BACKTRACK. Exclude last element from the subset and try the next valid one. currentSubSet.pop(); } // Return all subsets of a set. return allSubsets; } /** * Find power-set of a set using BACKTRACKING approach. * * @param {*[]} originalSet * @return {*[][]} */ export default function btPowerSet(originalSet) { return btPowerSetRecursive(originalSet); }