Sub topic 14
Backtracking: Exploring and Undoing Choices
This chapter assumes you know tree recursion, where one call makes several recursive calls, and recursion on trees. Backtracking uses the same branching shape. The difference is that it builds a partial solution step by step and undoes each step after exploring it.
The working model
Backtracking solves search problems: listing every permutation, every subset, or every valid arrangement. Each recursive call follows the same three steps:
- Choose one option that is still available.
- Explore by recursing with that choice added to the partial solution.
- Unchoose by removing the choice, so the next option starts from the same state.
The base case is a complete solution. When the partial solution is complete, the call records it and returns.
Permutations of a list
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]]The program keeps one current list and one used list for the whole search. It never builds a new copy at each level. Every append has a matching pop, and every used[i] = True has a matching reset. Because of these pairs, each call returns the shared state exactly as it found it. This is what lets the loop try the next option cleanly.
The search walks this tree depth first. Moving down an edge is a choose step. Returning up an edge is an unchoose step.
Pruning
Many problems add a constraint, such as "no two queens attack each other". You check the constraint before you recurse. If the partial solution is already invalid, skip that branch. This is called pruning. It cuts off whole subtrees, and on constrained problems it is usually what makes backtracking fast enough to use.
Common errors
| Mistake | Symptom |
|---|---|
| Appending `current` instead of `current[:]` | Every stored result is the same list, which is empty at the end |
| Forgetting `current.pop()` | Partial solutions keep growing and the output is wrong |
| Forgetting to reset `used[i]` | Later branches skip options, so results go missing |
| Checking the constraint only at the leaves | The output is correct, but the program explores far more of the tree than it needs to |
Exercise
In permutations([1, 2, 3]), what is printed if results.append(current[:]) is changed to results.append(current)? Explain why.
Show answer
It prints [[], [], [], [], [], []]. All six entries point to the same list object. Every append on that list is later undone by a pop, so when the search finishes the shared list is empty.
Exercise
Write subsets(items) that returns every subset of items by backtracking. At each index, the function should either include the item or skip it.
Show answer
def subsets(items): results, current = [], [] def backtrack(i): if i == len(items): results.append(current[:]) return current.append(items[i]) backtrack(i + 1) current.pop() backtrack(i + 1) backtrack(0) return results