Recursion & Backtracking
Calls that call themselves, trees of choices, and undoing a step to try the next one.
- trace a recursive call and its stack frames
- write subsets and permutations with choose-explore-un-choose
- solve N-Queens and explain how pruning helps
- decide when to avoid recursion in Python
Anatomy of a recursive function
A recursive function solves a problem by calling itself on a smaller version of the same problem. Two parts are always needed:
- Base case β an input so small that the answer is immediate. Without it the calls never stop.
- Recursive case β express the answer using the answer for a smaller input, and make sure each call really moves toward the base case.
Each call waits for the call below it, so Python keeps a call stack of unfinished calls. total(3) pushes total(3), total(2), total(1), total(0); then the answers flow back up: 0, 1+0, 2+1, 3+3.
What does this print?
def f(n):
if n == 0:
return "x"
return f(n - 1) + str(n)
print(f(3))What happens if a recursive function has no reachable base case?
Recursion as a tree of choices
Draw each call as a node and each recursive call as a child. For problems that ask for all arrangements, the tree is a map of decisions: at every node you choose one of several options, and a leaf is a finished answer.
Take the subsets of [a, b, c]. At each element you make one decision: include it or skip it. Three elements, two choices each: 2Β³ = 8 leaves β the 8 subsets. For permutations of 3 items you choose which unused item goes next: 3 Γ 2 Γ 1 = 6 leaves.
| Problem | Leaves | Tree width at depth d |
|---|---|---|
| subsets of n items | 2βΏ | 2 choices each (include / skip) |
| permutations of n items | n! | n β d unused items remain |
| combinations C(n, k) | n! / (k!(nβk)!) | choose in increasing order |
How many subsets does a set of 5 elements have?
How many permutations does a 4-letter word with all different letters have?
Backtracking: choose, explore, un-choose
Backtracking is recursion over a tree of choices, with one extra habit: after exploring a choice you undo it, so the shared state is exactly as it was before you try the next choice.
The backtracking template
out.append(path) stores a reference to the one list that keeps changing, so every entry ends up empty at the end. Write out.append(path[:]) (or list(path)).
Why do we call path.pop() after the recursive call?
What does this print?
out, path = [], []
def go(i):
if i == 2:
out.append(path[:])
return
for v in (7, 8):
path.append(v)
go(i + 1)
path.pop()
go(0)
print(out)What does this (buggy) version print?
out, path = [], []
def go(i):
if i == 2:
out.append(path) # no copy!
return
for v in (7, 8):
path.append(v)
go(i + 1)
path.pop()
go(0)
print(out)N-Queens: backtracking with pruning
Place n queens on an n Γ n board so none attack another (same row, column or diagonal). One queen per row, so the choice at row r is the column. Instead of trying all nβΏ placements, stop as soon as a queen is attacked β that is pruning.
The three sets make the attack test O(1): squares on the same β diagonal share r β c, and squares on the same β diagonal share r + c.
Two queens at (r1, c1) and (r2, c2) attack along a diagonal exactly whenβ¦
How many solutions does the 6-queens puzzle have?
Pruning: the difference between usable and hopeless
Backtracking is exponential in the worst case, so everything depends on cutting branches early. Compare two ways to count subsets of positive numbers that add up to a target:
With positive numbers, once the running total exceeds the target no extension can ever repair it β so the pruned search skips whole subtrees. Good pruning rules are cheap to test and never discard a valid answer. Sorting the input first often makes pruning much stronger (stop the loop when the next number is already too big).
Which rule is a valid prune when all numbers are positive and you need a sum of exactly target?
Which of these are typical backtracking problems?
Python limits and when to avoid recursion
Python allows about 1000 nested calls by default. A recursion that goes n deep for n = 10β΅ raises RecursionError. You have three options:
- Convert to a loop (when the recursion is just a counter, like
total(n)above) - Use an explicit stack (depth-first search over a big graph)
- Raise the limit with
sys.setrecursionlimitβ only when you are sure the depth stays modest, because very deep recursion can crash the interpreter.
lru_cache remembers results, so overlapping calls (as in Fibonacci) are computed once β that is memoisation, the first half of dynamic programming.
Why does naive recursive Fibonacci take exponential time?
Chapter challenge β Recursion & Backtracking
Every correct recursive function needsβ¦
What does this print? (type the exact output)
def f(n):
if n <= 1:
return 1
return f(n - 1) * n
print(f(5))How many subsets of {1, 2, 3, 4} are there (including the empty set)?
Order the steps inside the loop of a backtracking function.
A permutation generator stores out.append(path) instead of out.append(path[:]). What goes wrong?
What does pruning do?
How many permutations of 6 distinct items exist?
Which problems fit backtracking?
Practice on LeetCode
Generate-all problems: subsets, permutations, parentheses and N-Queens.
Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.
| Problem | Level | Practises | |
|---|---|---|---|
| Subsets β | Medium | include / skip decision tree: 2^n leaves | |
| Permutations β | Medium | choose an unused item at each level | |
| Combination Sum β | Medium | choose-explore-un-choose with pruning on the running total | |
| Generate Parentheses β | Medium | prune when closes would exceed opens | |
| Letter Combinations of a Phone Number β | Medium | one choice per digit | |
| N-Queens β | Hard | backtracking with row, column and diagonal sets |
Key takeaways
- A recursive function needs a base case and a call on a smaller input. The call stack remembers unfinished calls.
- Draw the calls as a tree of choices: subsets have 2βΏ leaves, permutations n!.
- Backtracking = choose, explore, un-choose, and record a COPY of the path when it is complete.
- Pruning cuts branches that cannot succeed; it is what makes N-Queens and Sudoku practical.
- Python recursion is limited to about 1000 frames; use loops, an explicit stack or
lru_cache(memoisation) when needed.