Remember what you already solved: recursion, memoization, and the algorithm
Lucas P. Cordova, Ph.D.
Willamette University | Fall 2026
BY THE END OF CLASS YOU CAN
Four questions you already know how to ask, and the one habit that answers them
Every one of these is a question about the best or the number of ways to make a sequence of choices. Each one is solved by the same habit: solve the small versions once, write them down, build up.
| The question | The choices | What dynamic programming computes |
|---|---|---|
| Turn-by-turn directions on one-way streets | which street to take next | shortest path on a DAG: last week's relaxation in topological order |
| Autocorrect on your phone | insert, delete, or swap a letter | edit distance between what you typed and each dictionary word |
| Lining up two DNA sequences | match, skip, or gap | the best alignment score (longest common subsequence) |
| Your LaTeX homework PDF | where to break each line | the paragraph with the least total badness (TeX's line breaker) |
| A sawmill cutting logs | where to cut | the cut pattern with the highest revenue (today) |
| Packing a resupply box for the PCT | take an item or leave it | the most calories under the weight limit (next week) |
Dynamic programming is recursion plus a notebook. Write every answer down the first time; read it every time after.
| Greedy (Dijkstra) | Dynamic programming | |
|---|---|---|
| How it decides | commits to the locally best choice and never looks back | tries every choice for the current subproblem, keeps the best |
| Why it is right | a proof that the local choice is safe (cut property, non-negative edges) | the recurrence itself: every option was considered |
| When it works | the problem has a safe greedy choice (rare, and you must prove it) | subproblems repeat and the best answer is built from best sub-answers |
| Cost | usually near-linear | number of subproblems times work per subproblem; polynomial |
| Example | MST, shortest paths with non-negative weights | stairs, road trip, log cutting (today); edit distance, knapsack (next) |
Counting ways: why plain recursion explodes, and the table that fixes it
The stairs up to Ford 102 have n steps. You climb one or two steps at a time. How many different ways are there to reach the top?
THE LAST MOVE INTO STEP 6 CAME FROM STEP 5 OR STEP 4.
def ways(steps: int) -> int:
if steps <= 1:
return 1
return ways(steps - 1) + ways(steps - 2)| n | ways(n) | calls made |
|---|---|---|
| 6 | 13 | 25 |
| 10 | 89 | 177 |
| 20 | 10,946 | 21,891 |
| 30 | 1,346,269 | 2,692,537 |
| 40 | 165,580,141 | 331,160,281 |
THE CALL TREE OF ways(6): 25 CALLS. ways(4) IS COMPUTED TWICE, ways(3) THREE TIMES, ways(2) FIVE TIMES.
The tree doubles with every two extra steps: about 1.6ⁿ calls. ways(40) takes a few minutes; ways(80) would outlast the semester.
from functools import lru_cache
@lru_cache(maxsize=None) # the notebook
def ways(steps: int) -> int:
if steps <= 1:
return 1
return ways(steps - 1) + ways(steps - 2)
# the same thing by hand:
memo: dict[int, int] = {}
def ways_memo(steps: int) -> int:
if steps <= 1:
return 1
if steps not in memo: # first time: compute
memo[steps] = ways_memo(steps - 1) + ways_memo(steps - 2)
return memo[steps] # every time: look upWITH A TABLE: 11 CALLS INSTEAD OF 25. AMBER = ANSWERED FROM THE TABLE.
import sys
from functools import lru_cache
@lru_cache(maxsize=None)
def ways(steps: int) -> int:
if steps <= 1:
return 1
return ways(steps - 1) + ways(steps - 2)
print(ways(40)) # 165580141, instantly
print(sys.getrecursionlimit()) # 1000
print(ways(1500)) # RecursionError: maximum
# recursion depth exceededways(1500) calls ways(1499), which calls ways(1498), and so on: 1500 calls are open before the first one returns and the first table entry is written. The table fills from the bottom of the stack up, so top-down is always as deep as the problem is long.
Try it: dp.html?mode=stairs&n=1500&variant=memo (watch the stack gauge cross the limit), then switch to bottom-up.
sys.setrecursionlimit(10_000) raises the ceiling. Past a few tens of thousands of frames the interpreter itself can run out of stack and crash, so this is a patch for homework, and the real fix is on the next slide.def ways_bottom_up(steps: int) -> int:
table = [0] * (steps + 1)
table[0] = table[1] = 1 # base cases first
for k in range(2, steps + 1): # smaller before larger
table[k] = table[k - 1] + table[k - 2]
return table[steps]| Memoized (top-down) | Bottom-up | |
|---|---|---|
| Order | whatever the recursion asks for | you choose: smaller subproblems first |
| Code | the recurrence plus a cache | a loop over the table |
| Work | only the subproblems actually needed | every subproblem in the table |
| Risk | recursion depth (Python stops near 1000) | none; and space can often shrink (keep two cells) |
A staircase has n steps and you climb 1 or 2 at a time. Give a recurrence for the number of ways to reach the top, with base cases, and the count for 6 steps. What is the running time with and without memoization? Is the memoized version safe to call with n = 1500 in Python?
“The number of ways to climb n steps taking 1 or 2 at a time satisfies ways(n) = ways(n − 1) + ways(n − 2). The base cases are ways(0) = 0 and ways(1) = 1, so the sequence is 0, 1, 1, 2, 3, 5, 8: there are 8 ways to climb 6 steps. With memoization this runs in O(n) time; without memoization it also runs in O(n) time, because each value is computed from the two before it. Memoized, ways(1500) is instant and safe, since only 1,500 values are stored.”
Six questions that turn a recurrence into an algorithm
| Ask | For the stairs |
|---|---|
| Subproblems. What smaller versions of the question will I store? How many? | ways(k) = ways to climb k steps; n + 1 of them |
| Relate. How does one subproblem's answer come from smaller ones? (What is the last choice?) | ways(k) = ways(k − 1) + ways(k − 2) |
| Order. Which subproblems must be done first? (A topological order of the dependencies.) | increasing k |
| Base cases. Which subproblems have a direct answer? | ways(0) = ways(1) = 1 |
| Original. Which subproblem (or combination) answers the real question? | ways(n) |
| Time. Subproblems × work per subproblem. | (n + 1) × O(1) = O(n) |
ways(k) NEEDS ways(k − 1) (GREY) AND ways(k − 2) (AMBER). SOURCES 0 AND 1 ARE THE BASE CASES.
Shortest paths on a DAG were computed by relaxing edges in topological order. That was dynamic programming: dist[v] = min over incoming edges of dist[u] + w(u, v).
A shortest path on a line, solved as a table
Driving I-5 from Salem to Ashland (236 miles) with a rule: at most 120 miles a day, then a hotel. Hotels cost different amounts in each town. Which towns do you stop in to spend the least?
| Ask | Answer |
|---|---|
| Subproblems | best(c) = least hotel money spent to arrive in town c; one per town |
| Relate | best(c) = hotel(c) + min over earlier towns p within 120 miles of best(p) |
| Order | towns from north to south along the road (increasing mile marker) |
| Base case | best(Salem) = 0 |
| Original | best(Ashland), with hotel(Ashland) = 0: no hotel on the night you arrive |
| Time | n towns × up to n earlier towns = O(n²); O(n) with the range rule |
Towns within 120 miles: Salem. from Salem: 0 + 110 = 110. Keep the smallest: best(Eugene) = $110, arriving from Salem.
| town | best | from |
|---|---|---|
| Salem | $0 | start |
| Eugene | $110 | Salem |
| Cottage Grove | · | · |
| Roseburg | · | · |
| Medford | · | · |
| Ashland | · | · |
Towns within 120 miles: Salem, Eugene. from Salem: 0 + 80 = 80; from Eugene: 110 + 80 = 190. Keep the smallest: best(Cottage Grove) = $80, arriving from Salem.
| town | best | from |
|---|---|---|
| Salem | $0 | start |
| Eugene | $110 | Salem |
| Cottage Grove | $80 | Salem |
| Roseburg | · | · |
| Medford | · | · |
| Ashland | · | · |
Towns within 120 miles: Eugene, Cottage Grove. from Eugene: 110 + 90 = 200; from Cottage Grove: 80 + 90 = 170. Keep the smallest: best(Roseburg) = $170, arriving from Cottage Grove.
| town | best | from |
|---|---|---|
| Salem | $0 | start |
| Eugene | $110 | Salem |
| Cottage Grove | $80 | Salem |
| Roseburg | $170 | Cottage Grove |
| Medford | · | · |
| Ashland | · | · |
best(Ashland) = $170. Follow 'from' backward: Ashland ← Roseburg ← Cottage Grove ← Salem. Two nights, Cottage Grove then Roseburg. Medford's $310 was computed and never used; that is normal.
| town | best | from |
|---|---|---|
| Salem | $0 | start |
| Eugene | $110 | Salem |
| Cottage Grove | $80 | Salem |
| Roseburg | $170 | Cottage Grove |
| Medford | $310 | Roseburg |
| Ashland | $170 | Roseburg |
Choices, a recurrence, a table, and reading the answer back
A mill has an 8-foot Douglas fir log and a price list by length. It can cut the log into any whole-foot pieces. Which cuts bring in the most money?
| length (ft) | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| price ($) | 1 | 5 | 8 | 9 | 10 | 17 | 17 | 20 |
| Ask | Answer |
|---|---|
| Subproblems | rev(L) = most money for a log of L feet; L = 0..n, so n + 1 of them |
| Relate | rev(L) = max1 ≤ i ≤ L ( price[i] + rev(L − i) ): try every first piece |
| Order | increasing L |
| Base case | rev(0) = 0 |
| Original | rev(n) |
| Time | n + 1 subproblems × O(n) choices each = O(n²) |
1 ft: 1 + rev(2) = 6; 2 ft: 5 + rev(1) = 6; 3 ft: 8 + rev(0) = 8. Best: rev(3) = $8, first piece 3 ft.
| L | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| rev | 0 | 1 | 5 | 8 | · | · | · | · | · |
| cut | — | 1 | 2 | 3 | · | · | · | · | · |
rev: BEST REVENUE FOR A LOG OF L FEET. cut: THE FIRST PIECE THAT ACHIEVED IT.
1 ft: 1 + rev(4) = 11; 2 ft: 5 + rev(3) = 13; 3 ft: 8 + rev(2) = 13; 4 ft: 9 + rev(1) = 10; 5 ft: 10 + rev(0) = 10. Best: rev(5) = $13, first piece 2 ft.
| L | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| rev | 0 | 1 | 5 | 8 | 10 | 13 | · | · | · |
| cut | — | 1 | 2 | 3 | 2 | 2 | · | · | · |
rev: BEST REVENUE FOR A LOG OF L FEET. cut: THE FIRST PIECE THAT ACHIEVED IT.
1 ft: 1 + rev(7) = 19; 2 ft: 5 + rev(6) = 22; 3 ft: 8 + rev(5) = 21; 4 ft: 9 + rev(4) = 19; 5 ft: 10 + rev(3) = 18; 6 ft: 17 + rev(2) = 22; 7 ft: 17 + rev(1) = 18; 8 ft: 20 + rev(0) = 20. Best: rev(8) = $22, first piece 2 ft.
| L | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| rev | 0 | 1 | 5 | 8 | 10 | 13 | 17 | 18 | 22 |
| cut | — | 1 | 2 | 3 | 2 | 2 | 6 | 1 | 2 |
rev: BEST REVENUE FOR A LOG OF L FEET. cut: THE FIRST PIECE THAT ACHIEVED IT.
| L | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| rev | 0 | 1 | 5 | 8 | 10 | 13 | 17 | 18 | 22 |
| cut | — | 1 | 2 | 3 | 2 | 2 | 6 | 1 | 2 |
rev: BEST REVENUE FOR A LOG OF L FEET. cut: THE FIRST PIECE THAT ACHIEVED IT.
def best_revenue(price: list[int], length: int) -> tuple[int, list[int]]:
rev = [0] * (length + 1) # rev[L]: best money for L feet
first_cut = [0] * (length + 1) # the first piece that achieved it
for L in range(1, length + 1): # smaller logs first
for piece in range(1, L + 1): # every possible first piece
candidate = price[piece] + rev[L - piece]
if candidate > rev[L]:
rev[L] = candidate
first_cut[L] = piece
pieces: list[int] = [] # read the answer backward
remaining = length
while remaining > 0:
pieces.append(first_cut[remaining])
remaining -= first_cut[remaining]
return rev[length], piecesYour turn, in pairs
A different mill, a different price list, a 6-foot log. (a) Fill the rev and cut rows for L = 0..6, showing every candidate for L = 4. (b) Read the best cut pattern back from the cut row. (c) The Sparks Center stairs allow 1, 2, or 3 steps at a time: write the six questions and compute ways(6).
| length (ft) | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| price ($) | 2 | 5 | 7 | 8 | 10 | 13 |
A 6-FOOT LOG, FIVE PLACES TO CUT OR NOT: 32 PATTERNS BY BRUTE FORCE.
What to keep, and what comes next