The Dynamic Programming Method
Divide and conquer breaks a problem into subproblems and combines their solutions. It works beautifully when the subproblems are independent. But we saw in the divide and conquer chapter that the naive recursive Fibonacci solves the same subproblems again and again, and becomes exponential. Dynamic programming keeps the idea of solving a problem through its subproblems, but solves each subproblem only once, storing its solution in a table for later use.
The name comes from Richard Bellman, who developed the technique in the 1950s; "programming" refers to filling in a table (as in "planning"), not to writing code.
- When divide and conquer is not suitable, and how dynamic programming fixes it.
- The two ways of applying dynamic programming: bottom-up (tables) and top-down (memoization).
- The principle of optimality and the steps to design a dynamic programming algorithm.
- Classic examples: Fibonacci, combinations, the 0/1 knapsack problem, the longest common subsequence and the edit distance.
Problems with Divide and Conquer
Divide and conquer divides the original problem into subproblems and combines their solutions. It has two drawbacks:
- It is not suitable when the number of subproblems is very high, because the complexity becomes non-polynomial (remember the subtraction schemes with ).
- It is not suitable when the subproblems are repeated, because the same subproblem is then solved several times in the same execution.
Fibonacci again
long fibonacci_dv(int n) {
if (n == 0) return 0;
else if (n == 1) return 1;
else return fibonacci_dv(n - 1) + fibonacci_dv(n - 2);
}
For , the call tree contains 25 calls, but only 7 different subproblems: . is computed 5 times, 8 times and 5 times:
The time is , exponential, but there are only different subproblems. If we store each result the first time we compute it, the exponential explosion disappears.
The Idea of Dynamic Programming
Dynamic programming, like divide and conquer, divides the original problem into subproblems and combines their solutions. The improvement is:
- each subproblem is solved only once, and its solution is stored for later use;
- the goal is to avoid calculating the same subproblem twice, usually by maintaining a table of known results.
Fibonacci with a table
long fibonacci_dp(int n) {
long[] f = new long[n + 1];
f[0] = 0;
f[1] = 1; // we know them
for (int i = 2; i <= n; i++)
f[i] = f[i - 1] + f[i - 2]; // each value is computed once, from known values
return f[n];
}
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | 2 | 3 | 5 | 8 |
Each cell is computed from the two previous ones: , , , , . The time drops from to .
🧠 Checkpoint: Calls versus cells
Question: How many calls does the naive recursive Fibonacci make to compute (with base cases and )? How many cells does the table of the dynamic programming version fill?
Answer: The naive version makes 21,891 calls to obtain . The table has only 21 cells, to , each computed once with one addition.
Divide and conquer versus dynamic programming
| Divide and conquer | Dynamic programming | |
|---|---|---|
| Direction | Descending (top-down): starts with the whole problem and divides it into subproblems | Usually ascending (bottom-up): starts with the smallest subproblems and composes their solutions until reaching the whole problem (memoization, below, is a top-down variant) |
| Subproblems | Should be independent | Overlap: the same subproblems appear many times |
| Repeated work | Recomputes repeated subproblems | Solves each subproblem once, storing its solution |
| Memory | The recursion stack | A table of results (plus, possibly, the stack) |
| Typical examples | Binary search, Mergesort, Quicksort | Fibonacci, combinations, knapsack, shortest paths |
Two Ways of Applying It
- Bottom-up (tabulation)
- Top-down (memoization)
The classic form of dynamic programming. The table is filled iteratively, from the smallest subproblems to the largest, in an order that guarantees that every value needed is already available. The fibonacci_dp method above is an example.
- No recursion, so no risk of stack overflow, and no function call overhead.
- Every subproblem is computed, even those that are not needed for the final answer.
- Requires thinking about the order in which the table is filled.
Keep the recursive divide and conquer algorithm, but remember (memoize) the result of each call: before computing a subproblem, check whether it is already in the table.
long[] memo; // memo[i] = -1 means "not computed yet"
long fibonacciMemo(int n) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n]; // already known: reuse it
memo[n] = fibonacciMemo(n - 1) + fibonacciMemo(n - 2);
return memo[n];
}
- Very easy to obtain from a recursive solution: the recursion is unchanged.
- Only the subproblems that are really needed are computed.
- Uses the call stack, so the recursion depth can be a problem for large inputs.
Both approaches have the same asymptotic complexity: the number of different subproblems multiplied by the cost of computing each one from the solutions of smaller subproblems. This is the general rule to analyze dynamic programming algorithms.
🧠 Checkpoint: Top-down or bottom-up?
Question: You need the solution of one large problem, but only a small fraction of its subproblems are actually reached from it. Which form of dynamic programming fits better, and why?
Answer: Top-down (memoization): it computes only the subproblems that are really needed, while bottom-up fills the whole table. Its price is the recursion: the call stack may become too deep for large inputs.
The Principle of Optimality
Dynamic programming is widely used to solve optimization problems, and here it relies on a key property, formulated by Bellman as the principle of optimality:
In an optimal sequence of decisions, every subsequence must also be optimal.
In other words, an optimal solution of a problem is built from optimal solutions of its subproblems. For example, if the shortest route from Oviedo to Madrid goes through León, then its part from Oviedo to León must be the shortest route from Oviedo to León (otherwise, replacing it with a shorter one would give a shorter route to Madrid).
When the principle holds, we can write a recurrence that expresses the optimal value of a problem in terms of the optimal values of its subproblems, and then fill a table with it. When it does not hold, dynamic programming cannot be applied in this way. For example, the longest simple path between two cities does not satisfy it: the longest path from A to C through B is not necessarily formed by the longest paths from A to B and from B to C, which may share cities.
Compare with greedy algorithms: both require optimal substructure, but a greedy algorithm commits to one choice at each step, while dynamic programming considers all the choices and keeps the best one, using the stored solutions of the subproblems.
How to Design a Dynamic Programming Algorithm
- Characterise the subproblems. Decide what a subproblem is and what its parameters are. For example: "the maximum value that can be carried using only the first objects with a capacity ".
- Write the recurrence. Express the solution of a subproblem in terms of the solutions of smaller subproblems, including the base cases.
- Choose the table and the order. Store the solution of each subproblem in a table (a vector, a matrix...) and decide the order in which to fill it, so that every value needed has already been computed.
- Compute the value of the optimal solution, usually in the last cell filled.
- Reconstruct the solution itself, if needed, by tracing back through the table which choice produced each optimal value (for example, which objects go in the knapsack, not only their total value).
- Analyze the complexity: number of cells × cost per cell, both in time and in memory.
The next lesson follows these six steps for every problem, starting with simple ones (binomial coefficients) and ending with the knapsack and string problems.
Often a cell depends only on the previous row (or the previous few values). Then it is enough to keep one or two rows instead of the whole table: the iterative Fibonacci that keeps only the last two values is the dynamic programming solution with the table reduced to two variables, memory. The price is that reconstructing the solution (not just its value) usually needs the whole table.
Beyond the Course: Dynamic Programming Everywhere
Dynamic programming appears in many fields:
- Route planning and robotics: from a map of the environment and a goal, dynamic programming computes the best path from every possible starting location at once (a policy), which is valuable when movements may fail and the robot or the car must re-plan constantly. The short film Dynamic Programming - Artificial Intelligence for Robotics explains it with the example of a self-driving car.
- Bioinformatics: aligning DNA or protein sequences (a variant of the edit distance of the next lesson).
- Text processing: spelling correctors, the
difftool that compares files, line breaking in word processors. - Shortest paths: the Floyd-Warshall and Bellman-Ford algorithms.
- Operations research and economics: inventory management, resource allocation, investment planning.
- Filling the table in the wrong order. A cell can only be computed when the cells it depends on are already filled.
- Forgetting the base cases or the extra row and column. Tables usually have size to include the empty subproblem.
- Memoizing without checking the table first. Look up the stored value before recursing, or nothing is saved.
- Using dynamic programming when subproblems do not repeat. Then divide and conquer is simpler and just as fast.
Summary
- Divide and conquer is not suitable when subproblems are numerous and repeated. Dynamic programming solves each subproblem once and stores its solution in a table.
- Divide and conquer is descending; dynamic programming is ascending: it starts from the smallest subproblems.
- Bottom-up dynamic programming fills a table iteratively; top-down (memoization) adds a table to a recursive algorithm. Both cost (number of subproblems) × (cost per subproblem).
- In optimization problems, dynamic programming relies on the principle of optimality: optimal solutions are made of optimal solutions of subproblems.
- Design: characterise the subproblems, write the recurrence with its base cases, choose the table and its filling order, compute the value, reconstruct the solution, and analyze the cost.
Practice
- 🌳 Count the repetitions. Draw the full call tree of the naive Fibonacci for . How many calls does it have, and how many different subproblems? (You should find 41 calls for only 8 subproblems.)
- 📝 Memoize. Add memoization to the naive recursive Fibonacci, using a
HashMap<Integer, Long>, and compare its times with the naive version for . - 🔁 Two variables. Write the bottom-up Fibonacci keeping only the last two values. What is its memory complexity?
- 🗺️ Principle of optimality. Draw a small graph with four nodes in which the longest simple path from A to C passes through B, but is not formed by the longest simple paths from A to B and from B to C. Why does this not happen with shortest paths?
Errors, suggestions and public questions open a form on GitHub, visible to everyone.