Algorithms · Backtracking

Subsets

List every way to pick some of the items.

The problem

Return every subset of nums (every way to pick some of the numbers, including none and all). The numbers are all different; the order doesn’t matter.

check([1, 2, 3])[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
check([0])[[], [0]]
Backtracking. Try, undo, try again. A maze: walk until you hit a dead end, step back, try the next turn.

Now ask: what if there were a billion?

At 64 items there are more subsets than grains of sand on Earth. When a problem’s answer explodes like this, real systems stop listing everything and search smartly instead: pruning, good-enough answers, or a SAT solver.

Aim for O(2ⁿ)🧩 classic

Think it through

For each number, how many choices are there?

  • Two: in or out
  • As many as there are numbers
Show the answer

Two: in or out. Two choices per number, so n numbers give 2 × 2 × … = 2ⁿ subsets. No trick makes that smaller: you must list them all.

After exploring “with this number”, what must you do before going back up?

  • Nothing
  • Take the number out again
Show the answer

Take the number out again. Choose, explore, un-choose. That last step is what makes it backtracking: one list is shared by every branch, so each branch must tidy up after itself.

Stuck? 3 nudges, smallest first
  1. For each number there are exactly two choices: leave it out, or put it in.
  2. Explore “out” first, then add the number, explore “in”, and remove it again before going back up.
  3. In explore: explore(i + 1, chosen), chosen.append(nums[i]), explore(i + 1, chosen), chosen.pop().

The fast way

Try it yourself before you open this.

Show the fast version
def subsets(nums):take a list of different numbers
out = []every subset we find
def explore(i, chosen):decide about nums[i]; chosen = picked so far
if i == len(nums):decided about every number
out.append(chosen[:])save a copy of this subset
returngo back
explore(i + 1, chosen)choice 1: leave nums[i] out
chosen.append(nums[i])choice 2: put it in…
explore(i + 1, chosen)…and explore from there
chosen.pop()undo, before going back
explore(0, [])start with nothing chosen
return outall the subsets

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with backtracking