Sub topic 14
Backtracking: Exploring and Undoing Choices
This chapter assumes you can read Python functions, you are comfortable with the base case and recursive case, and you can follow how the call stack runs nested calls. It also builds on tree recursion, where one call makes several recursive calls.
Backtracking is a way to search through all possible solutions one choice at a time. You make a choice and recurse to explore what follows from it. Then you undo the choice so the next option starts from the same state. When a partial solution can't lead anywhere useful, you abandon it early. Puzzles, scheduling, permutations, subsets, and constraint problems such as Sudoku all fit this pattern.
The Working Model: Choose, Explore, Unchoose
Every backtracking function repeats the same three steps inside a loop over the available options:
- Choose: add an option to the current partial solution and update any bookkeeping.
- Explore: call the function recursively to extend that partial solution.
- Unchoose: reverse exactly what step 1 did.
The base case fires when the partial solution is complete. At that point you record it and return.
This differs from the tree recursion you saw with Fibonacci in one way. The calls share one mutable state, such as a list that grows and shrinks, and they don't each build fresh values. Sharing state is cheap, but it only works if every change is undone before the next option is tried.
Generating Permutations
A permutation is one ordering of a set of items. To build every ordering of [1, 2, 3], pick any unused item for the first position, then any remaining item for the second, and so on.
def permutations(items):
results = []
current = []
used = [False] * len(items)
def backtrack():
if len(current) == len(items):
results.append(current[:])
return
for i in range(len(items)):
if used[i]:
continue
used[i] = True
current.append(items[i])
backtrack()
current.pop()
used[i] = False
backtrack()
return results
print(permutations([1, 2, 3]))
# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]Here is how the three steps map onto the code:
| Step | Code | State change |
|---|---|---|
| Choose | `used[i] = True` and `current.append(items[i])` | One more item placed |
| Explore | `backtrack()` | Deeper call fills later positions |
| Unchoose | `current.pop()` and `used[i] = False` | State restored exactly |
| Base case | `len(current) == len(items)` | Record a copy, return |
The unchoose lines run in the reverse order of the choose lines. With two independent pieces of state the order doesn't matter much, but mirroring the order is a good habit when the changes depend on each other.
The Search Tree
Each call is a node in a search tree. The path from the root to a node is the list of choices made so far. When a call returns, control goes back up one level and the loop moves to the next sibling. That return is the "backtrack."
The call stack only ever holds one root-to-node path at a time, so stack depth equals the length of a solution (here 3). The total work is much larger. There are n! leaves, and copying each leaf costs O(n), so generating all permutations costs O(n · n!) time. Backtracking doesn't make exponential problems cheap. It visits the search space in an orderly way and uses little memory while doing it.
A Second Shape: Subsets
Permutations ask "which item goes next?" Subsets ask "which items do I include?" To avoid producing the same subset in two orders, each call only considers items at or after a start index.
def subsets(items):
results = []
current = []
def backtrack(start):
results.append(current[:])
for i in range(start, len(items)):
current.append(items[i])
backtrack(i + 1)
current.pop()
backtrack(0)
return results
print(subsets([1, 2, 3]))
# [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]Every node in this search tree is a valid answer, so the function records current on entry instead of waiting for a "complete" state. The base case is implicit. When start == len(items), the loop body never runs and the call returns.
Pruning: Abandoning Dead Ends Early
Backtracking beats brute-force enumeration through pruning, which means returning as soon as a partial solution can't succeed. The example below finds every combination of candidates (each reusable) that sums to a target. Sorting first lets the loop stop once a candidate is too large.
def combination_sum(candidates, target):
candidates = sorted(candidates)
results = []
current = []
def backtrack(start, remaining):
if remaining == 0:
results.append(current[:])
return
for i in range(start, len(candidates)):
c = candidates[i]
if c > remaining:
break
current.append(c)
backtrack(i, remaining - c)
current.pop()
backtrack(0, target)
return results
print(combination_sum([2, 3, 6, 7], 7)) # [[2, 2, 3], [7]]The break cuts off whole subtrees. Since the list is sorted, every later candidate is also too large. Passing i rather than i + 1 allows reuse of the same candidate. Passing remaining as an argument means it needs no explicit undo, because each call gets its own copy in its own stack frame.
Common Errors
Recording the list instead of a copy
def broken_permutations(items):
results, current, used = [], [], [False] * len(items)
def backtrack():
if len(current) == len(items):
results.append(current) # bug: no copy
return
for i in range(len(items)):
if not used[i]:
used[i] = True
current.append(items[i])
backtrack()
current.pop()
used[i] = False
backtrack()
return results
print(broken_permutations([1, 2, 3])) # [[], [], [], [], [], []]All six entries point to the same list object, and that list is empty by the end of the search. Use current[:] or list(current) when recording.
Incomplete undo
If you forget one reversal, such as used[i] = False, state leaks into sibling branches. The search silently skips options, and the output is too short rather than raising an error.
Undoing in the wrong place
Every unchoose must run on every path after its matching choose. If the code returns early between a choose and its undo, for example after finding a solution, the undo is skipped. Put the base-case check at the top of the function, before any choice is made in that call.
Exercises
Exercise
In the permutations function, suppose you delete the line used[i] = False but keep current.pop(). What does permutations([1, 2, 3]) return, and why?
Show answer
It returns [[1, 2, 3]]. The first path marks all three items as used and never unmarks them. When control returns to earlier levels, every remaining loop iteration finds its item already marked and skips it, so no other branch is explored.
Exercise
Adapt the subsets function into combinations(items, k), which returns only the subsets of exactly size k. Where does the base case go, and what pruning can you add?
Show answer
Check at the top of backtrack: if len(current) == k, append a copy and return. Otherwise loop i from start to len(items), append items[i], call backtrack(i + 1), then pop. To prune, stop the loop once too few items remain to fill the subset, that is, when len(items) - i < k - len(current). For combinations([1, 2, 3, 4], 2) the result is [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]].
Exercise
In combination_sum, why does remaining need no explicit undo step while current does?
Show answer
remaining is an integer argument, so each call has its own value in its own stack frame, and returning discards it. current is one list shared by every call, so any append must be reversed with pop before the next option is tried.