DP recipe: recursion to tabulation
Dynamic programming is recursion that remembers. Write the answer for a state in terms of smaller states, store each answer the first time it is computed (memoisation), or fill a table from the smallest states up (tabulation). When each state only needs the last row or the last few values, keep just those and save memory.
How to recognise it
- A brute-force recursion solves the same smaller problem many times.
- The question asks for a count, a best value, or whether something is possible.
- Choices made one step at a time, where only a little information about the past matters.
Four steps
- State. What do you need to know to describe one subproblem? (n; or n and r; or a position and a remaining budget.)
- Choice. What is decided at that state, and what smaller state does each choice lead to?
- Recurrence. Combine the choices: add for counting, take max or min for optimising, OR for possibility.
- Order. Memoise the recursion, or fill a table so smaller states come first.
fib(n): memo[n] if known
else memo[n] = fib(n - 1) + fib(n - 2)
table: f[0] = 0; f[1] = 1; for i in 2..n: f[i] = f[i - 1] + f[i - 2]
| Problem | State | Recurrence |
|---|---|---|
| nCr | (n, r) | C(n-1, r) + C(n-1, r-1) |
| nPr | (n, k) | n × (n-1) × … (k factors) |
| Catalan | n | sum of C(i) × C(n-1-i) |
Saving memory
If row i only uses row i - 1, keep one row. If f(i) uses the last two values, keep two numbers.
Common mistakes
- A state that leaves out something the answer depends on.
- Filling a table in an order where a needed value is not ready yet.
- Forgetting the modulo when the problem asks for one.
Problems
- Binomial CoefficientProblemmediumguide ready
- Permutation CoefficientProblemmediumguide ready
- Program for nth Catalan Numbermediumguide ready