Subsets
The problem
Section titled “The problem”You get an array of distinct integers. Return all of its subsets (the power set), with no duplicates. Any order is fine.
nums = [1, 2, 3] -> [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]There are 2^n of them, because each number is either in or out.
Key insight
Section titled “Key insight”You can’t avoid producing 2^n answers, so the goal is to produce each one exactly once.
Walk a decision tree: a growing path is already a valid subset at every node, so
record it immediately instead of waiting for a leaf.
To avoid duplicates, only add numbers that sit to the right of the last one you took.
That is the start index. [1, 2] gets built, but [2, 1] never does, because after
choosing 2 you only look at numbers after it.
Each step is the same three moves: choose a number, recurse, un-choose it.
Show solutionHide solution
def subsets(nums: list[int]) -> list[list[int]]: res, path = [], []
def backtrack(start: int) -> None: res.append(path[:]) # every path is a valid subset for i in range(start, len(nums)): path.append(nums[i]) # choose backtrack(i + 1) # explore: only look right, so no repeats path.pop() # un-choose
backtrack(0) return resexport function subsets(nums: number[]): number[][] { const res: number[][] = []; const path: number[] = [];
function backtrack(start: number): void { res.push([...path]); // every path is a valid subset for (let i = start; i < nums.length; i++) { path.push(nums[i]); // choose backtrack(i + 1); // explore: only look right, so no repeats path.pop(); // un-choose } }
backtrack(0); return res;}import java.util.ArrayList;import java.util.List;
class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> res = new ArrayList<>(); backtrack(nums, 0, new ArrayList<>(), res); return res; }
private void backtrack(int[] nums, int start, List<Integer> path, List<List<Integer>> res) { res.add(new ArrayList<>(path)); // every path is a valid subset for (int i = start; i < nums.length; i++) { path.add(nums[i]); // choose backtrack(nums, i + 1, path, res); // explore: only look right, so no repeats path.remove(path.size() - 1); // un-choose } }}Complexity
Section titled “Complexity”- Time: O(n · 2^n) — there are 2^n subsets, and copying each one into the result costs up to O(n).
- Space: O(n) — recursion depth and
pathare at most n deep. The returned answer itself is O(n · 2^n), not counted as extra.
Watch out for
Section titled “Watch out for”- Copy the path.
res.append(path)stores a reference, and every entry ends up empty after the final un-choose. Usepath[:]/new ArrayList<>(path)/[...path]. - Recurse with
i + 1, notstart + 1. Passingstart + 1lets a number be picked again, so you get repeated subsets and invalid ones like[2, 2]. - Don’t forget the empty subset. Recording at the top of the function covers it.
Variations
Section titled “Variations”Subsets II (LeetCode 90)
Section titled “Subsets II (LeetCode 90)”The array may contain duplicates, but the answer must not repeat a subset. The trick:
sort first. Inside the loop, skip nums[i] when i > start and nums[i] == nums[i - 1],
so the same value is only used first at each level.
Combinations (LeetCode 77)
Section titled “Combinations (LeetCode 77)”Return all ways to choose k numbers from 1..n. The trick: the same template, but
record only when len(path) == k. Prune when too few numbers remain to fill the path.
Letter Combinations of a Phone Number (LeetCode 17)
Section titled “Letter Combinations of a Phone Number (LeetCode 17)”Given digits, return every letter string they could spell. The trick: the choice at
depth d is one of the letters for digit d. Recurse with d + 1, no start index
needed, and record at depth len(digits).