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.
path (what we hold)
saved subsets
1def subsets(nums):2 res, path = [], []3 def dfs(i):4 if i == len(nums):5 res.append(path[:])6 return7 path.append(nums[i])8 dfs(i + 1)9 path.pop()10 dfs(i + 1)11 dfs(0)12 return res
Variables
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.
| Problem | Choice at each step | Prune when |
|---|---|---|
| All subsets | Take or leave nums[i] | (never: every path is valid) |
| Combination sum | Reuse or move past nums[i] | Running sum > target |
| Subsets with duplicates | Take or leave, skipping repeated values | Same 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
Recursion
A recursive function solves a problem by calling itself on a smaller version of it, until it reaches a base case it can answer directly. Each pending call waits on the call stack, so recursion costs memory too.
8 min read →Permutations
To build every ordering, fill positions one by one: at each position try every element not used yet, recurse, then undo. There are n! permutations, so it only works for small n.
8 min read →Traversals
A tree is a node with up to two subtrees, so most problems are recursion: solve the left, solve the right, combine. DFS (inorder, preorder, postorder) uses the call stack; BFS (level order) uses a queue. All visit each node once: O(n); space is O(h) for DFS and O(width) for BFS.
9 min read →