How can I generate all possible subsets from an array of unique integers?
For instance, if I have powerSet[1,2,3]
, the expected output should be
[[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]
I've tried a recursive approach:
function powerset(array) {
let set = [[]];
powersetHelper(array, [], set);
return set;
}
function powersetHelper(array, subset, set) {
if (array.length === 0) return;
for (let i = 0; i < array.length; i++) {
subset.push(array[i]);
set.push(subset);
}
let newArr = array.slice(1);
powersetHelper(newArr, [], set)
}
However, this is not providing the correct solution and instead returning
[[], [1, 2, 3], [1, 2, 3], [1, 2, 3], [2, 3], [2, 3], [3]]
. What am I doing wrong?
I also attempted an iterative solution:
function powerset(array) {
let subset = [];
let set = [[]];
while (array.length > 0) {
for (let j = 0; j < array.length; j++) {
let num = array[j];
subset.push(num);
set.push(subset);
}
array = array.slice(1);
}
return set;
}
Surprisingly, this implementation is giving me a similar incorrect result as seen below. Despite following a similar logic to my recursive function, it's still producing unexpected output:
[
[],
[1, 2, 3, 2, 3, 3],
[1, 2, 3, 2, 3, 3],
[1, 2, 3, 2, 3, 3],
[1, 2, 3, 2, 3, 3],
[1, 2, 3, 2, 3, 3],
[1, 2, 3, 2, 3, 3]
]