Summary: Dynamic Programming
Everything on one page, to review the chapter before moving on.
Key ideas
- When the subproblems are numerous and repeated, divide and conquer wastes time. Dynamic programming solves each subproblem once and stores its solution in a table (The Dynamic Programming Method).
- Bottom-up dynamic programming fills the table iteratively, from the smallest subproblems; top-down (memoization) adds a table to the recursive algorithm.
- The cost is (number of subproblems) × (cost per subproblem).
- In optimization problems it relies on the principle of optimality: optimal solutions are made of optimal solutions of subproblems.
- Design steps: characterise the subproblems, write the recurrence and its base cases, choose the table and its filling order, compute the value, reconstruct the solution, and analyze the cost.
- If a cell depends only on the previous row, one or two rows are enough instead of the whole table.
At a glance
| Problem | Subproblems | Complexity |
|---|---|---|
| Fibonacci | , | |
| Combinations | ||
| 0/1 knapsack | : first objects, capacity | , pseudo-polynomial |
| Change | : first coin values, amount | , pseudo-polynomial |
| River | : from dock to dock | |
| Longest common subsequence | : prefixes of both strings | |
| Edit distance | : prefixes of both strings |
The recurrences are in Classic Problems.
When to use it
- The problem has overlapping subproblems and optimal substructure.
- The number of different subproblems is reasonable (polynomial, or pseudo-polynomial in a numeric value such as the capacity).
- Compared with greedy: slower, but it does not depend on a heuristic being optimal. Compared with backtracking: much faster when it applies.
Saved only in your browser
Questions, or something wrong?
Errors, suggestions and public questions open a form on GitHub, visible to everyone.