Sub topic 1
From Recursion to Repeated Work
Prerequisites
This chapter assumes you can write Python functions and loops, use recursion with base cases, work with lists and dictionaries, and read Big-O notation.
Recursion that repeats itself
Many problems split naturally into smaller versions of themselves. The Fibonacci numbers are the standard example: fib(n) = fib(n - 1) + fib(n - 2). A direct recursive version is correct but slow. Counting the calls shows why:
from collections import Counter
calls = Counter()
def fib(n):
calls[n] += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(20)) # 6765
print(calls[2]) # 4181The function computes fib(2) 4,181 times to produce a single answer. The total number of calls grows roughly as 1.618^n, which is exponential time.
Spotting overlapping subproblems
A problem has overlapping subproblems when different branches of the recursion call the function with the same arguments. To check, draw a small call tree and look for repeated nodes. Merge sort has no overlap because its two halves are disjoint, so caching would not help it. Fibonacci repeats nodes everywhere, so caching each result once removes most of the work.
Optimal substructure: building answers from sub-answers
A problem has optimal substructure when you can build an optimal answer from optimal answers to its subproblems. In coin change, the fewest coins for amount a is 1 plus the fewest coins for a - c, where c is the best choice of last coin. Longest simple path in a graph does not have this property. Two optimal sub-paths can share a vertex, and joining them does not give a valid path.
Dynamic programming needs both properties: overlap makes caching worthwhile, and optimal substructure makes the recurrence correct.
Defining the state, recurrence, and base cases
Every DP solution starts with three decisions:
| Piece | Meaning | Fibonacci |
|---|---|---|
| State | The parameters that identify a subproblem | `n` |
| Recurrence | How a state's answer comes from smaller states | `fib(n) = fib(n-1) + fib(n-2)` |
| Base cases | States answered directly, without recursion | `fib(0) = 0`, `fib(1) = 1` |
Exercise
You climb a staircase of n steps, taking 1 or 2 steps at a time. Define the state, recurrence, and base cases for the number of distinct ways to reach the top. Does the problem have overlapping subproblems?
Show answer
The state is n, the number of steps remaining. The recurrence is ways(n) = ways(n - 1) + ways(n - 2), because the first move is either 1 or 2 steps. The base cases are ways(0) = 1 and ways(1) = 1. Yes, the subproblems overlap: ways(n - 2) is reached both directly and through ways(n - 1), the same pattern as in Fibonacci.