Mediumbacktracking
Subsets
Problem (restated)
Return all subsets of a distinct integer array (power set).
Intuition
At each index: skip or take, then recurse. Record path at every node.
Approaches
Include/exclude DFS
UnverifiedTime O(n * 2^n)Space O(n)
Idea. dfs(i): append path; for j>=i take nums[j], dfs(j+1), undo.
Walkthrough. [1,2,3] → 8 subsets including [] and full set.
Trade-offs. Bit mask iteration is O(n·2^n) too; backtracking is the template.
Solution
export function subsets(nums: number[]): number[][] {
const res: number[][] = [];
const path: number[] = [];
const dfs = (start: number) => {
res.push([...path]);
for (let i = start; i < nums.length; i++) {
path.push(nums[i]!);
dfs(i + 1);
path.pop();
}
};
dfs(0);
return res;
}
export function subsets(nums: number[]): number[][] {
const res: number[][] = [];
const path: number[] = [];
const dfs = (start: number) => {
res.push([...path]);
for (let i = start; i < nums.length; i++) {
path.push(nums[i]!);
dfs(i + 1);
path.pop();
}
};
dfs(0);
return res;
}
Template connection
Backtracking choose/explore/undo.
Reflection
- At each index you take the value or you skip it. That is 2ⁿ leaves. Moving the index forward stops the same subset from showing up as a permutation.
- Append a copy. Pushing the same list lets the next choice edit the subsets you already saved.
- An empty array answers
[[]].