Skip to content

Subsets

MediumLeetCode #78Time O(n · 2^n)Space O(n)

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.

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 res
  • 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 path are at most n deep. The returned answer itself is O(n · 2^n), not counted as extra.
  • Copy the path. res.append(path) stores a reference, and every entry ends up empty after the final un-choose. Use path[:] / new ArrayList<>(path) / [...path].
  • Recurse with i + 1, not start + 1. Passing start + 1 lets 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.

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.

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).