Skip to the workspace
Pebellslearn by building
Backtracking  ›  Lesson

Choose or Skip: Recursion That Builds Subsets

Subsets 15 minBacktracking lists every option by recursing through the choices, changing a shared path, exploring, and undoing the change, and for subsets each item branches into take it or leave it.

leetcode / Choose or Skip: Recursion That Builds Subsets

Explore each scene at your own pace.

01 · The rule

The rule

Choose or Skip: Recursion That Builds Subsets

A pizza place offers three extra toppings: olive, onion and pepper. The menu designer wants to print every possible combination, from a plain pizza to one with all three. That is not "find the best one"; it is "list them all", and listing everything is the job of backtracking.

The rule

At each item, branch twice: take it, or leave it.

Walk through the items in order. For each one there are exactly two futures: the pizza has this topping, or it does not. Explore the first future fully, come back, and explore the second. When you run out of items, the choices you made form one complete combination. Recursion expresses this directly:

def all_subsets(items):
    result, path = [], []
    def explore(i):
        if i == len(items):             # base case: every item decided
            result.append(path[:])      # save a COPY of the current choices
            return
        path.append(items[i])           # choose: take item i
        explore(i + 1)
        path.pop()                      # un-choose: undo it
        explore(i + 1)                  # skip item i
    explore(0)
    return result

Three parts make every backtracking function:

  • The base case stops the recursion: here, when all items are decided.
  • Choose, explore, un-choose: change path, recurse, then undo the change exactly, so the next branch starts from a clean state.
  • Save a copy: path keeps changing after you record it, so store path[:], not path itself.

Recursion itself is just a function solving a smaller copy of the same problem: explore(i) means "decide the items from position i onwards". Each call hands on a problem one item smaller, which is why every branch is guaranteed to reach the base case.

Each item doubles the number of results, so n items give 2ⁿ subsets. That is fine for 20 items (about a million) and hopeless for 40 (about a trillion), which is why backtracking problems come with small limits.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.