forked from trekhleb/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
btPowerSet.js
41 lines (36 loc) · 1.69 KB
/
btPowerSet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* @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);
}