Given a set of distinct integers array, return all possible subsets.
Given a set of distinct integers array myArray
, return all possible subsets (the power set).
Example 1:
Input: myArray = [1, 2, 3];
Output: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
Solution using Javascript:
const combine = (myArray, index, partial, results) => {
if (index === myArray.length) {
results.push(partial);
return;
}
combine(myArray, index + 1, partial, results);
combine(myArray, index + 1, partial.concat([myArray[index]]), results);
};
const subsets = (myArray) => {
const results = [];
combine(myArray, 0, [], results);
return results;
};
Test Cases
describe('subsets', () => {
test('should return all possible subsets', () => {
const myArray = [1, 2, 3];
expect(subsets(myArray)).toEqual([[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]);
});
});