Dynamic programming, the intuitive way

CategoryAlgorithms Published Reading1 min read

One idea

Dynamic programming means never solving the same subproblem twice. Write each answer down once, and look it up the next time you need it.

Fibonacci

from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

One decorator turns exponential time into linear time.

Spotting a DP problem

  1. The problem breaks into smaller problems of the same shape.
  2. Those smaller answers get reused many times.

If you see both, write the recurrence and start filling the table.

Comments