Dynamic Programming: Classic Problems
This lesson applies the design steps of dynamic programming to several classic problems: counting combinations, the 0/1 knapsack problem, the change with any coin system, the cheapest travel on a river, and two problems on strings, the longest common subsequence and the edit distance. The implementations of the course examples are in the course repository.
- How to turn a recursive formula with overlapping subproblems into a table: Pascal's triangle.
- How to solve the 0/1 knapsack problem optimally, fill its table by hand and recover which objects to take.
- What a pseudo-polynomial algorithm is.
- Two classic dynamic programming algorithms on strings: LCS and edit distance.
Combinations
In mathematics, a combination is a way of selecting things out of a larger group of , where (unlike permutations) the order does not matter. For example, given three fruits (an apple, an orange and a pear), there are three combinations of two: apple and orange, apple and pear, and orange and pear. The number of combinations is the binomial coefficient:
Computing it with factorials is risky: overflows a long for , even when the result is small. A better way uses the recurrence behind Pascal's triangle:
(either a given element is in the selection, and we choose the other among the remaining ; or it is not, and we choose all among the remaining ).
🧠 Checkpoint: Combinations of 9 elements taken 5 at a time
Question: How many combinations of 9 elements taken 5 at a time are there?
Answer: .
Divide and conquer: exponential
The recurrence translates directly into a recursive method:
public long combinationsRecursive(int n, int k) {
if (k == 0 || k == n) return 1;
return combinationsRecursive(n - 1, k - 1) + combinationsRecursive(n - 1, k);
}
It has the same problem as Fibonacci: the same subproblems are solved many times. Since every call ends in a base case that returns 1, and the result is the sum of those 1s, computing requires calls. We measured it:
| Value | Recursive calls | Recursive time | Dynamic programming time | |
|---|---|---|---|---|
| 184,756 | 369,511 | 2 ms | 0.3 ms | |
| 10,400,600 | 20,801,199 | 47 ms | 0.04 ms | |
| 155,117,520 | 310,235,039 | 581 ms | 0.1 ms | |
| 601,080,390 | 1,202,160,779 | 2,317 ms | 0.07 ms |
Dynamic programming: Pascal's triangle
The different subproblems are the values with and . Store them in a table, filled row by row, from top to bottom: each cell is the sum of the cell above and the cell above-left.
public long combinationsDP(int n, int k) {
long[][] table = new long[n + 1][k + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(i, k); j++) {
if (j == 0 || j == i)
table[i][j] = 1; // borders of the triangle
else
table[i][j] = table[i - 1][j - 1] + table[i - 1][j]; // Pascal's rule
}
}
return table[n][k];
}
The first rows of the table (Pascal's triangle):
| \ | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| 0 | 1 | |||||
| 1 | 1 | 1 | ||||
| 2 | 1 | 2 | 1 | |||
| 3 | 1 | 3 | 3 | 1 | ||
| 4 | 1 | 4 | 6 | 4 | 1 | |
| 5 | 1 | 5 | 10 | 10 | 5 | 1 |
| 6 | 1 | 6 | 15 | 20 | 15 | 6 |
Complexity. There are cells, each computed with one addition: time and memory (or memory keeping only the previous row). Compare with the exponential growth of the recursive version.
ProofPascal's ruleThe 0/1 Knapsack Problem
We met the knapsack problem in the greedy chapter. Now the objects cannot be fragmented: each object is either taken entirely or left. We have objects, each with a weight and a value , and a backpack that can carry a total weight not exceeding ; we want to maximize the total value. We saw that no greedy heuristic is optimal for this version. Dynamic programming is.
Data
Three objects and a weight limit :
| Object | 1 | 2 | 3 |
|---|---|---|---|
| Weight | 6 | 5 | 5 |
| Value | 8 | 5 | 5 |
The greedy algorithm by value per weight would take object 1 (ratio , versus 1 for the others), and then nothing else fits: value 8. Can we do better?
The subproblems and the recurrence
Subproblems: let be the maximum value we can carry using only the first objects, with a weight limit . The solution of the problem is , here .
Recurrence: for object there are only two options: leave it, or take it (if it fits). If we leave it, the best is . If we take it, we gain , and the remaining capacity must be used in the best possible way with the first objects (the principle of optimality): . Hence:
The value for a negative capacity simply means that an object that does not fit can never be taken.
ProofThe 0/1 knapsack recurrence is correctFilling the table
The table has a row for each number of objects (from 0 to ) and a column for each weight limit (from 0 to ). It is filled row by row, since each row only depends on the previous one:
| \ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 (no objects) | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1 (object 1: ) | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 8 | 8 | 8 | 8 |
| 2 (object 2: ) | 0 | 0 | 0 | 0 | 0 | 5 | 8 | 8 | 8 | 8 | 8 |
| 3 (object 3: ) | 0 | 0 | 0 | 0 | 0 | 5 | 8 | 8 | 8 | 8 | 10 |
Some cells, step by step:
- : with capacity 6, object 1 fits.
- : with capacity 5, only object 2 fits.
- : objects 1 and 2 together weigh 11, so the best is object 1 alone.
- 10: taking object 3 and using the remaining capacity 5 in the best way (object 2) beats object 1.
The optimal value is 10, better than the 8 of the greedy algorithm.
Recovering the objects
The table gives the optimal value. To know which objects to take, trace back from : if , object was taken, so continue from ; otherwise, it was not, so continue from .
- : object 3 is taken; continue from .
- : object 2 is taken; continue from .
- : object 1 is not taken.
Solution: objects 2 and 3, with total weight 10 and value 10.
int knapsack01(int maxWeight, int[] weights, int[] values) {
int n = weights.length;
int[][] v = new int[n + 1][maxWeight + 1]; // row 0: no objects, all zeros
for (int i = 1; i <= n; i++)
for (int j = 0; j <= maxWeight; j++) {
v[i][j] = v[i - 1][j]; // leave object i
if (weights[i - 1] <= j) // take it, if it fits
v[i][j] = Math.max(v[i][j], v[i - 1][j - weights[i - 1]] + values[i - 1]);
}
return v[n][maxWeight];
}
🧠 Checkpoint: Fill a table yourself
Question: Four objects with weights 3, 2, 1, 4 and values 6, 4, 5, 10. What is the maximum value with ?
Answer: 15. Several combinations reach it: objects 1, 2 and 3 (weights , values ), or objects 3 and 4 (weights , values ). Fill the table to check it.
Complexity: pseudo-polynomial
The table has cells, each computed in constant time: in time and memory (memory can be reduced to by keeping a single row, at the cost of not being able to reconstruct the objects).
This looks polynomial, but it depends on the value of , not on its size. is written with about bits, so is exponential in the size of the input, just like the naive greatest common divisor of the divide and conquer chapter. Such algorithms are called pseudo-polynomial: excellent when is moderate (a few thousand), impractical when is huge (for example, weights in grams of a cargo ship). No algorithm that is polynomial in the size of the input is known for the 0/1 knapsack problem.
The Problem of the Change
In the greedy chapter we saw that always taking the largest coin that fits gives the fewest coins for the euro, but fails for other coin systems. Dynamic programming solves the problem for any coin system.
Problem. Pay an amount with the fewest possible coins, choosing from coin values , with an unlimited supply of each. We assume , so that every amount can be paid.
The subproblems and the recurrence
Subproblems: let be the minimum number of coins needed to pay the amount using only the first coin values. The answer is .
Recurrence: for coin value there are two options. Either we do not use it, and the best is ; or we use at least one coin of value , and then we still have to pay , possibly with more coins of the same value, so the best is . The difference with the knapsack is in that last term: it stays in the same row , because a coin can be used many times.
Filling the table
With coins of 1, 4, 5 and 12 and , the table has one row per coin value and one column per amount from 0 to 15. Each row is filled from left to right, because each cell may use the cell positions to its left in the same row:
| Coins \ Amount | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| up to 1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| up to 4 | 0 | 1 | 2 | 3 | 1 | 2 | 3 | 4 | 2 | 3 | 4 | 5 | 3 | 4 | 5 | 6 |
| up to 5 | 0 | 1 | 2 | 3 | 1 | 1 | 2 | 3 | 2 | 2 | 2 | 3 | 3 | 3 | 3 | 3 |
| up to 12 | 0 | 1 | 2 | 3 | 1 | 1 | 2 | 3 | 2 | 2 | 2 | 3 | 1 | 2 | 3 | 3 |
The answer is 3 coins. To know which ones, walk back from the last cell: if a cell equals the one above it, the coin of its row was not needed, so move up; otherwise one coin of its row was used, so subtract its value and move left. From we move up, and in row "up to 5" we take three coins of 5: 5 + 5 + 5. The greedy algorithm would take 12 + 1 + 1 + 1, four coins.
public int change(int amount, int[] coins) { // coins sorted, coins[0] == 1
int n = coins.length;
int[][] c = new int[n][amount + 1];
for (int j = 0; j <= amount; j++)
c[0][j] = j; // only coins of value 1
for (int i = 1; i < n; i++)
for (int j = 0; j <= amount; j++) {
c[i][j] = c[i - 1][j]; // do not use coins[i]
if (j >= coins[i])
c[i][j] = Math.min(c[i][j], 1 + c[i][j - coins[i]]); // use it once more
}
return c[n - 1][amount];
}
Complexity. The table has cells, each filled in : time and memory. As in the knapsack, it is pseudo-polynomial: it depends on the value of . Only the previous row is needed, so the memory can be reduced to a single array of positions.
With the table it is easy to check where the greedy algorithm fails: for the coins 1, 4, 5, 12, 20 and 50, it gives more coins than necessary for 10 of the amounts from 1 to 100, the first ones being 8 (greedy 5 + 1 + 1 + 1, optimal 4 + 4) and 15.
Cheaper Travel on the River
A river has docks, numbered from 0 (upstream) to (downstream). At each one you can rent a boat to go to any other dock downstream; going upstream is impossible. A table of fees gives the price of a trip from dock to dock , for . A direct trip may cost more than a combination of shorter trips, changing boats at an intermediate dock. We want the minimum cost for every pair of docks .
The subproblems and the recurrence
The cheapest way from to either goes directly, or stops for the first time at some dock between them; then it must continue from to in the cheapest way, and also reach from in the cheapest way (the principle of optimality):
Each depends on pairs that are closer together, so the table can be filled by increasing distance , or, as in the code below, with going from the last dock upwards and from downstream.
An example
With five docks and these fees (only the upper triangle makes sense):
| From \ To | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| 0 | 3 | 8 | 12 | 20 |
| 1 | 4 | 7 | 15 | |
| 2 | 2 | 9 | ||
| 3 | 4 |
the table of minimum costs is:
| From \ To | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| 0 | 3 | 7 | 9 | 13 |
| 1 | 4 | 6 | 10 | |
| 2 | 2 | 6 | ||
| 3 | 4 |
For example, , and the cheapest trip from the first to the last dock costs 13 instead of the direct fee of 20, stopping at every dock: . Storing, for each pair, the dock that gave the minimum allows recovering the route.
public int[][] minimumCosts(int[][] fee) {
int n = fee.length;
int[][] cost = new int[n][n];
for (int i = n - 2; i >= 0; i--)
for (int j = i + 1; j < n; j++) {
int best = fee[i][j]; // direct trip
for (int k = i + 1; k < j; k++) // first stop at k
best = Math.min(best, cost[i][k] + cost[k][j]);
cost[i][j] = best;
}
return cost;
}
Complexity. There are about pairs, and each one tries up to intermediate docks: time and memory. It is the same idea as Floyd's algorithm (Floyd, 1962) for shortest paths between all pairs of nodes of a graph, simplified by the fact that the boats only go downstream.
Beyond the Course: Dynamic Programming on Strings
Two classic problems show how dynamic programming handles sequences.
Longest common subsequence (LCS)
A subsequence of a string is obtained by deleting some characters without changing the order of the rest. The longest common subsequence of two strings is the longest string that is a subsequence of both. For example, for ALGORITHM and ALTRUISM, an LCS is ALRIM, of length 5.
Subproblems: = length of the LCS of the first characters of and the first characters of .
If the last characters match, they are part of the LCS; otherwise, one of them is not, and we keep the best of discarding either one. The table has cells: . The diff tool that compares versions of a file is based on this idea, applied to lines instead of characters.
Edit distance
The edit distance (or Levenshtein distance) between two strings is the minimum number of single-character insertions, deletions and substitutions needed to transform one into the other. For example, KITTEN → SITTING needs 3 operations: substitute K by S, substitute E by I, insert G.
with and . The complete table for KITTEN (rows) and SITTING (columns):
| ∅ | S | I | T | T | I | N | G | |
|---|---|---|---|---|---|---|---|---|
| ∅ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| K | 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| I | 2 | 2 | 1 | 2 | 3 | 4 | 5 | 6 |
| T | 3 | 3 | 2 | 1 | 2 | 3 | 4 | 5 |
| T | 4 | 4 | 3 | 2 | 1 | 2 | 3 | 4 |
| E | 5 | 5 | 4 | 3 | 2 | 2 | 3 | 4 |
| N | 6 | 6 | 5 | 4 | 3 | 3 | 2 | 3 |
Spelling correctors use it to suggest the closest dictionary words, and bioinformatics uses weighted variants to align DNA sequences.
- Calling polynomial. It is pseudo-polynomial: is a value, exponential in its number of digits.
- Using the previous row when coins are unlimited. In the change problem, using one more coin of the same value stays in the same row.
- Computing only the optimal value. To give the solution, keep the table (or the decisions) and reconstruct it backwards.
- Mixing string indices and table indices. refers to prefixes of lengths and , so character is at position .
Summary
| Problem | Subproblems | Recurrence (idea) | Complexity |
|---|---|---|---|
| Fibonacci | , | ||
| Combinations | |||
| 0/1 knapsack | : first objects, capacity | leave or take object | , pseudo-polynomial |
| Change | : first coin values, amount | skip coin , or use one more (same row) | , pseudo-polynomial |
| River | : from dock to dock | direct trip, or first stop at | |
| LCS | : prefixes of both strings | match, or discard one character | |
| Edit distance | : prefixes of both strings | delete, insert or substitute |
Practice
- 🔺 Pascal. Run
combinationsDPandcombinationsRecursivefrom the course repository for increasing with , and check the number of calls . - 🎒 Knapsack by hand. Fill the knapsack table for the data of the checkpoint (), and recover the objects chosen by tracing back from . Which of the two optimal combinations do you obtain?
- 💾 One row. Rewrite the knapsack algorithm using a single array of positions. In which direction must the inner loop run so that each object is used at most once?
- 💰 The change with one array. Rewrite the change algorithm with a single array of positions. Why can the inner loop go from left to right here, while in the knapsack it had to go the other way?
- 🚣 The route on the river. Extend the river algorithm to store the intermediate dock of each minimum, and write a method that prints the cheapest route between two docks.
- 🔤 LCS. Implement the LCS algorithm, including the reconstruction of the subsequence, and test it with two versions of a short text.
Errors, suggestions and public questions open a form on GitHub, visible to everyone.