Skip to main content

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​

ProblemSubproblemsComplexity
FibonacciF(i)F(i), 0≤i≤n0 \le i \le nO(n)O(n)
CombinationsC(i,j)C(i, j)O(n⋅k)O(n \cdot k)
0/1 knapsackV(i,j)V(i, j): first ii objects, capacity jjO(n⋅W)O(n \cdot W), pseudo-polynomial
ChangeC(i,j)C(i, j): first ii coin values, amount jjO(n⋅A)O(n \cdot A), pseudo-polynomial
RiverC(i,j)C(i, j): from dock ii to dock jjO(n3)O(n^3)
Longest common subsequenceL(i,j)L(i, j): prefixes of both stringsO(∣a∣⋅∣b∣)O(\lvert a \rvert \cdot \lvert b \rvert)
Edit distanceD(i,j)D(i, j): prefixes of both stringsO(∣a∣⋅∣b∣)O(\lvert a \rvert \cdot \lvert b \rvert)

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
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.