3.7.7 · D3Algorithm Paradigms

Worked examples — Memoization (top-down DP) — recursive + memo dict

2,567 words12 min readBack to topic

Before anything, a promise about vocabulary. A state is the complete description of a subproblem — the set of argument values that fully decides its answer. A memo (or cache) is a dictionary whose key is that state and whose value is the already-computed answer. Everything on this page is: pick the state, write the recurrence, cache by the state, store before returning.


The scenario matrix

Every memoization problem lives in one of these cells. The examples underneath are labelled with the cell they cover.

# Case class What is new / tricky Covered by
A 1-D state, 2-way branch the textbook shape Ex 1
B Base case at zero (degenerate input) what does n = 0 mean? Ex 1, Ex 2
C 1-D state, k-way branch recurse over a loop, not two fixed calls Ex 3
D 2-D state (tuple key) key must hold both variables Ex 4
E Negative / out-of-range state guard before you index Ex 5
F Choice = max/min, not sum combine is not always + Ex 6
G Real-world word problem translate English → recurrence Ex 7
H Exam twist: stale-key bug why a wrong key silently lies Ex 8
I Limiting behaviour / complexity count distinct states Ex 9

Ex 1 — Fibonacci at a boundary (cells A, B)


Ex 2 — Climbing Stairs, why (cell B, contrast with Ex 1)


Ex 3 — Coin-change count, a k-way branch (cell C)


Ex 4 — Grid unique paths, a tuple key (cell D)


Ex 5 — A state that can go negative (cell E)


Ex 6 — Max-sum, where combine is max not + (cell F)


Ex 7 — Word problem: decode-ways (cell G, real world)


Ex 8 — Exam twist: the stale-key bug (cell H)


Ex 9 — Limiting behaviour: counting distinct states (cell I)


Recall One-line takeaways per cell

Base value = half the DP ::: Ex 1 vs Ex 2 have identical recurrences, different answers. k-way branch = loop of additions ::: Ex 3, Ex 7. 2-D state = tuple key ::: Ex 4; a wrong partial key silently lies, Ex 8. Guard base cases before recursing ::: Ex 5 avoids negative indices. combine is max/min for optimisation, sum for counting ::: Ex 6. Time = distinct states × work per state ::: Ex 9.

Connections