diff --git a/src/algorithms/sets/power-set/btPowerSet.js b/src/algorithms/sets/power-set/btPowerSet.js index 1cf2d196..2007c124 100644 --- a/src/algorithms/sets/power-set/btPowerSet.js +++ b/src/algorithms/sets/power-set/btPowerSet.js @@ -6,16 +6,23 @@ * @return {*[][]} - All subsets of original set. */ function btPowerSetRecursive(originalSet, allSubsets = [[]], currentSubSet = [], startAt = 0) { - // In order to avoid duplication we need to start from next element every time we're forming a - // subset. If we will start from zero then we'll have duplicates like {3, 3, 3}. + // 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. + // 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 form all other subsets for the current subset. + + // 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 one. + + // BACKTRACK. Exclude last element from the subset and try the next valid one. currentSubSet.pop(); }