Algorithms Playbook
PatternTime O(n · 2ⁿ) · Space O(n)9 min read

Backtracking: subsets and combinations

Explore every possibility by making a choice, going deeper, and undoing the choice. The decision tree behind subsets, combination sum and most "generate all…" problems.

In short

When a problem asks for all the ways to do something, walk a tree of choices with recursion: choose → explore → undo. For subsets each number is either in or out, so the tree has 2ⁿ leaves.

The idea: a tree of choices

For [1, 2, 3], decide about each number in turn: take it or leave it. Every complete sequence of decisions is one subset. Drawn out, the decisions form a binary tree, and recursion walks it depth-first.

The part that makes it backtracking is the undo: after exploring the "take 1" branch you remove 1 from the path so the "leave 1" branch starts from a clean state. Without it the branches would contaminate each other.

Subsets: choose, explore, undo
Speed
011223i

path (what we hold)

0∅

saved subsets

0∅
[]decision tree: each level decides one number
1def subsets(nums):
2 res, path = [], []
3 def dfs(i):
4 if i == len(nums):
5 res.append(path[:])
6 return
7 path.append(nums[i])
8 dfs(i + 1)
9 path.pop()
10 dfs(i + 1)
11 dfs(0)
12 return res
Start: 3 numbers, each is either in or out. That is 2^3 = 8 subsets. We explore every choice, then go back (backtrack).

Variables

i0
path[]
saved0
Step 1/39· Calls: 1
Backtracking = a depth-first walk over a tree of choices. The `undo` line is what makes it work: after exploring a branch, put things back exactly as they were.

The template

def backtrack(state):
    if is_complete(state):
        results.append(copy(state))   # copy! state keeps changing
        return
    for choice in available_choices(state):
        apply(choice)       # choose
        backtrack(state)    # explore
        undo(choice)        # undo
  • Always copy the path when you save it (path[:], [...path], new ArrayList<>(path)). Saving the reference saves a list that later becomes empty.
  • The depth of the recursion is the number of decisions; the space is O(n) for the path (not counting the output).
  • Time is the number of leaves times the cost of copying one: O(n · 2ⁿ) for subsets.

Combinations and pruning

"Combination sum" (pick numbers that add up to a target) is the same tree with a goal: stop as soon as the sum reaches the target, and prune when it goes over. Pruning cuts whole branches that can't lead to a result, which is usually the difference between passing and timing out.

ProblemChoice at each stepPrune when
All subsetsTake or leave nums[i](never: every path is valid)
Combination sumReuse or move past nums[i]Running sum > target
Subsets with duplicatesTake or leave, skipping repeated valuesSame value as the previous one at this level

Key takeaways

  • 01"Generate all…" problems are a depth-first walk over a tree of choices.
  • 02Choose, explore, undo: the undo keeps branches independent.
  • 03Copy the path when you save it.
  • 04Prune branches that can't succeed; sorting helps with duplicates.

Check your understanding

1 of 3

How many subsets does a set of n distinct numbers have?

Related topics