Learn computing fundamentals, programming, algorithms, systems, and software engineering.
Dynamic Programming (DP) is a technique for solving problems by breaking them into overlapping subproblems, solving each subproblem once, and storing the answer so it is never recomputed. The name is misleading — it has nothing to do with "dynamic" in the everyday sense; it means solving a problem by filling in a table of saved results. The classic introduction is Fibonacci. A naive recursive solution computes the same values again and again and becomes impossibly slow. DP fixes this with one simple idea: remember the answers you have already found. There are two ways to fill the table. Memoization starts at the top and caches results as recursion returns. Tabulation builds the table bottom-up, from the smallest cases to the answer. Both give the same result; they differ only in direction. This lesson shows you how to recognise a DP problem, how to define the state, and how to move from a slow recursion to a fast, correct solution.
Dynamic Programming solves a problem by splitting it into overlapping subproblems, solving each one once, and caching the results. It applies when a problem has two properties: optimal substructure and overlapping subproblems.
Fibonacci is defined as F(n) = F(n-1) + F(n-2). Naive recursion recomputes the same values exponentially many times.
A problem has optimal substructure when the optimal answer can be built from optimal answers to its subproblems. In Fibonacci, F(5) is built from F(4) and F(3); if those are correct, F(5) is correct.
| Plain recursion | Dynamic Programming | |
|---|---|---|
| Repeated work | Recomputes subproblems | Computes each once |
| Memory | Call stack only | A table of saved results |
| Time | Often exponential | Usually polynomial |
| Typical use | Divide-and-conquer (no overlap) | Overlapping subproblems |
Memoization keeps the recursive structure but stores each result in a cache, returning the saved value instead of recomputing.
Tabulation fills an array from the base cases upward, eliminating recursion entirely.
The "state" is the information that fully describes a subproblem. For Fibonacci the state is just n. The "transition" is the rule that combines smaller states into a bigger one.
Memoization and tabulation are both O(n); the naive version is exponential.
Find the fewest coins that sum to a given amount. The state is the remaining amount.
3
fib_memo(30) is instant because each value is computed once.
832040