Learn / Dynamic programming

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

  1. State. What do you need to know to describe one subproblem? (n; or n and r; or a position and a remaining budget.)
  2. Choice. What is decided at that state, and what smaller state does each choice lead to?
  3. Recurrence. Combine the choices: add for counting, take max or min for optimising, OR for possibility.
  4. 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]
ProblemStateRecurrence
nCr(n, r)C(n-1, r) + C(n-1, r-1)
nPr(n, k)n × (n-1) × … (k factors)
Catalannsum 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

0 of 3 solved

Check yourself

What makes plain recursion for Fibonacci slow?

What is a 'state' in DP?

Tabulation fills states in which order?

Why does C(n, r) = C(n - 1, r) + C(n - 1, r - 1)?