Recursion and backtracking
A recursive function solves a problem by calling itself on a smaller version of the same problem. It's the natural way to work with trees, nested data and "try every possibility" problems. Backtracking is recursion that builds a solution step by step and undoes choices that lead nowhere.
The two parts of every recursive function
- Base case: a version small enough to answer directly.
- Recursive case: shrink the problem and call yourself.
How the calls stack up
Each call waits on the call stack until the smaller call returns:
Forget the base case, or fail to shrink the problem, and the stack grows until Python stops it:
Python's default limit is about 1,000 calls deep. For very deep problems (a linked list of a million nodes), use a loop or an explicit stack instead.
Divide and conquer
Split the problem in halves, solve each half recursively, combine the answers. Fast exponentiation computes x**n in O(log n) multiplications:
Merge sort (next lesson) and binary search work the same way.
Repeated work and memoisation
The obvious recursive Fibonacci recomputes the same values over and over, and its cost explodes as O(2ⁿ):
Caching results (memoisation) turns it into O(n). That's the core idea of dynamic programming, which gets its own lesson.
Backtracking
Backtracking explores choices like a maze: go down a path, and if it fails, step back and try the next one. The template:
def backtrack(partial):
if partial is a complete solution:
record it
return
for choice in available choices:
make the choice
backtrack(partial + choice)
undo the choiceAll subsets
n items have 2ⁿ subsets, so any algorithm that lists them all is at least O(2ⁿ).
Permutations
Pruning: combination sum
Find combinations of coin values that add up to a target. Pruning (stopping as soon as a path can't work) is what makes backtracking practical:
N-Queens
Place N queens on an N×N board so no two attack each other: the textbook backtracking puzzle.
Practice
- Write a recursive
flatten(nested)that returns a flat list. - Generate all valid combinations of
npairs of parentheses (for n = 3:((())),(()()),(())(),()(()),()()()). - Solve a word search: does a word exist in a grid of letters, moving up/down/left/right without reusing a cell?
1.What happens if a recursive function has no reachable base case?
2.Why is the naive recursive Fibonacci so slow?
3.What does "pruning" mean in backtracking?