|
6 | 6 | *@return {*[][]} - All subsets of original set.
|
7 | 7 | */
|
8 | 8 | functionbtPowerSetRecursive(originalSet,allSubsets=[[]],currentSubSet=[],startAt=0){
|
9 |
| -//In order to avoid duplication we need to start from next element every time we're forming a |
10 |
| -//subset. If we will start from zero then we'll have duplicates like {3, 3, 3}. |
| 9 | +//Let's iterate over originalSet elements that may be added to the subset |
| 10 | +//without having duplicates. The value of startAt prevents adding the duplicates. |
11 | 11 | for(letposition=startAt;position<originalSet.length;position+=1){
|
12 |
| -// Let's push current element to the subset. |
| 12 | +// Let's push current element to the subset |
13 | 13 | currentSubSet.push(originalSet[position]);
|
| 14 | + |
14 | 15 | // Current subset is already valid so let's memorize it.
|
| 16 | +// We do array destruction here to save the clone of the currentSubSet. |
| 17 | +// We need to save a clone since the original currentSubSet is going to be |
| 18 | +// mutated in further recursive calls. |
15 | 19 | allSubsets.push([...currentSubSet]);
|
16 |
| -// Let's try to form all other subsets for the current subset. |
| 20 | + |
| 21 | +// Let's try to generate all other subsets for the current subset. |
| 22 | +// We're increasing the position by one to avoid duplicates in subset. |
17 | 23 | btPowerSetRecursive(originalSet,allSubsets,currentSubSet,position+1);
|
18 |
| -// BACKTRACK. Exclude last element from the subset and try the next one. |
| 24 | + |
| 25 | +// BACKTRACK. Exclude last element from the subset and try the next valid one. |
19 | 26 | currentSubSet.pop();
|
20 | 27 | }
|
21 | 28 |
|
|