-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpowerset.js
More file actions
41 lines (33 loc) · 873 Bytes
/
powerset.js
File metadata and controls
41 lines (33 loc) · 873 Bytes
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
// Time O(n*2^n)
// Space O(n*2^n)
// function poweset(array) {
// const subsets = [[]];
// for (let num of array) {
// const length = subsets.length;
// for (let i = 0; i < length; i++) {
// const currentSubset = subsets[i];
// subsets.push(currentSubset.concat(num));
// }
// }
// return subsets;
// }
// recursive solution
// runs in the same time/space complexity
function powerset(array, idx = null) {
if (idx === null) {
idx = array.length - 1;
}
if (idx < 0) {
return [[]];
}
const ele = array[idx];
const subsets = powerset(array, idx - 1);
const length = subsets.length;
for (let i = 0; i < length; i++) {
const currentSubset = subsets[i];
subsets.push(currentSubset.concat(ele));
}
return subsets;
}
const array = [];
console.log(powerset(array));