Version: 0.6.22
2. Dynamic Programming#
- Lecture:
Lecture 7.2
(slides)- Objectives:
Understand what is a dynamic programming, when it applies, and how to apply it
- Concepts:
Dynamic programming: Memoïzation and bottom-up traversal
- Implementation:
Branch-and-bound makes a search faster by not looking at the hopeless parts of the tree. Dynamic programming speeds up recursive algorithms in a different way: By not solving the same problem twice. It applies when a problem breaks down into smaller problems that overlap. The best way to see it is on a famous example.
Note
A word about “programming”. In dynamic programming, the word “programming” has nothing to do with writing code. In the 1950s, when Richard Bellman introduced the method, it meant planning, as in “linear programming” or “mathematical programming”: finding the best plan. Dynamic programming is, first of all, a method to optimize, that is, to find the best solution among many, and to do so without trying them all.
2.1. A Slow Recursion#
The Fibonacci numbers start with 0 and 1, and every other number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. The definition is recursive, and so is the most direct algorithm:
function fibonacci(n):
if n = 0: return 0
if n = 1: return 1
return fibonacci(n - 1) + fibonacci(n - 2)
It is short, and correct, but surprisingly slow. Computing the 50th
number, 12 586 269 025, takes tens of seconds on a laptop, and the 60th
would take over an hour. Why? Look at the calls that
fibonacci(5) makes, on Fig. 2.49.
Fig. 2.49 The calls made to compute fibonacci(5). The ones in orange
compute something that is already computed elsewhere in the tree.#
The same numbers are computed again and again: fibonacci(3) twice,
fibonacci(2) three times, fibonacci(1) five times. And the
repetition gets worse as the tree grows. Each additional number multiplies
the number of calls by about 1.6: 177 calls for the 10th number, 21 891
for the 20th, and over 40 billion for the 50th. Yet, there are only
51 different numbers to compute, from fibonacci(0) to
fibonacci(50). How can we avoid doing the same work again?
2.2. Memoization#
A simple idea: write down each result when we compute it, and look
it up before computing it again. We keep the results in a cache, a
table that associates a number \(n\) with fibonacci(n). This
is called memoization (from “memo”, as in a note to remember).
cache ← empty table
function fibonacci(n):
if n = 0: return 0
if n = 1: return 1
if n is in cache: return cache[n]
result ← fibonacci(n - 1) + fibonacci(n - 2)
cache[n] ← result
return result
Fig. 2.50 shows the calls for
fibonacci(5). The first time we need a number, we compute it. The
next time, the cache answers immediately, and we do not explore that part
of the tree again. Instead of 15 calls, we make 9.
Fig. 2.50 The calls made to compute fibonacci(5) with memoization. The
ones in green are answered by the cache, without any further call.#
The gain is spectacular. There are only \(n + 1\) different numbers to compute, and each of them is computed once. The number of calls therefore grows in step with \(n\), and no longer explodes: 99 calls for the 50th number, instead of 40 billion. It now runs in microseconds.
Implementation in Java
The recursion straight from the definition, and the same with a
cache. In Java, a Map associates each number with its result.
1// Straight from the definition
2public long recursive(int n) {
3 calls++;
4 if (n == 0) {
5 return 0;
6 }
7 if (n == 1) {
8 return 1;
9 }
10 return recursive(n - 1) + recursive(n - 2);
11}
12
13// The same, but we remember the numbers we have already computed (memoization)
14public long memoized(int n) {
15 return memoized(n, new HashMap<>());
16}
17
18private long memoized(int n, Map<Integer, Long> cache) {
19 calls++;
20 if (n == 0) {
21 return 0;
22 }
23 if (n == 1) {
24 return 1;
25 }
26 if (cache.containsKey(n)) {
27 return cache.get(n);
28 }
29 long result = memoized(n - 1, cache) + memoized(n - 2, cache);
30 cache.put(n, result);
31 return result;
32}
2.3. Bottom-Up#
There is another way to look at the problem. To compute
fibonacci(50), we need fibonacci(49) and fibonacci(48), which
need the numbers before them, and so on, down to fibonacci(0) and
fibonacci(1). Why not start from there? We compute the numbers in
order, from the smallest to the one we want, and keep them in a table
(Fig. 2.51). We start from what we already know,
the initial state: fibonacci(0) and fibonacci(1), in red. When we
need a number, it is already in the table.
Fig. 2.51 Computing the Fibonacci numbers bottom-up. The first two cells, in red, are the initial state. Each other cell only needs the two cells before it.#
function fibonacci(n):
table[0] ← 0
table[1] ← 1
for i from 2 to n:
table[i] ← table[i - 1] + table[i - 2]
return table[n]
There is no recursion anymore, just a loop, and still each number is computed once. These two approaches, memoization (start from the problem we want to solve, and remember the results) and bottom-up (start from the smallest problems, and build up to the one we want), are called dynamic programming. Both trade memory for time: We keep the results of the smaller problems to avoid computing them again.
Implementation in Java
1// We compute the numbers in order, from the smallest, and keep them in a
2// table (bottom-up)
3public long bottomUp(int n) {
4 var table = new long[Math.max(n + 1, 2)];
5 table[0] = 0;
6 table[1] = 1;
7 for (int i = 2; i <= n; i++) {
8 table[i] = table[i - 1] + table[i - 2];
9 }
10 return table[n];
11}
2.4. Back to the Knapsack#
Let us now go back to the knapsack problem of the previous lecture: A box that carries 10 kg, and items that each have a weight and a value (the music instruments, the laptop, the books and the cooking tools). What is the highest value we can put in the box? We have seen that we can think about the items one after the other: For each of them, we can leave it, or take it if it fits. Whichever we choose, what remains to solve is a smaller problem of the same kind. This is a recursion:
function best(i, room):
if there is no item from i on:
return 0
leave ← best(i + 1, room)
if item i weighs more than room:
return leave
take ← value of item i + best(i + 1, room - weight of item i)
return the maximum of leave and take
best(0, 10)
Notice that best has only two parameters: which items remain to be
decided (from item \(i\) on), and how much room remains in the
box. What we chose for the previous items does not matter anymore,
except through the room it has left. This is what we call a
subproblem, and, as for the Fibonacci numbers, different paths may lead
to the same one.
In our example with four items, the tree is small, and no two paths lead to the same subproblem. But consider three items, of 2, 3 and 5 kg, in a box of 10 kg (Fig. 2.52). Taking the first two items, or only the third one, leaves the same room, 5 kg. Whatever we chose to get there, the problem that remains is exactly the same.
Fig. 2.52 The room left in the box after each choice. In orange, two different sets of choices lead to the same problem: 5 kg of room, and no more items to decide.#
With more items, the effect is dramatic. For a box of 15 kg and twenty light items, the recursion makes about 200 000 calls, and solves the same subproblems again and again. Yet, a subproblem is just a pair (item, room), so there are at most “number of items” \(\times\) “room + 1” different ones: Here, \(20 \times 16 = 320\). With memoization, we make fewer than 500 calls.
The bottom-up version fills a table, with one row per set of remaining items, and one column per amount of room (Fig. 2.53). We start from the bottom, where there are no more items and the value is 0: This is the initial state, in red. Then we go up, one row after the other. Each cell is the better of the two choices: leave the item (the cell right below), or take it (its value, plus the cell below for the room that remains). The answer is at the top right.
Fig. 2.53 The table for the items of the lecture. The bottom row, in red, is the initial state. The answer, 16 000 NOK, is the better of leaving the music instruments (7 000, the cell below) and taking them (9 000, plus 7 000 for the 8 kg left).#
If we want to know which items to take, and not only the value, we walk back from the answer: At each cell, we check which of the two choices gave its value. The table has one cell per item and per amount of room, so we solve the problem with about \(n \times C\) computations, for \(n\) items and a capacity of \(C\), instead of \(2^n\). But beware: The table grows with the capacity. If we measured the weights in grams instead of kilograms, it would be a thousand times bigger.
Implementation in Java
The recursion, and the version with memoization. Here, a subproblem is identified by the item and the room that remain, and the cache associates them with the best value:
1// The best value we can get with the given capacity
2public int recursive(int capacity) {
3 return recursive(0, capacity);
4}
5
6private int recursive(int index, int capacity) {
7 calls++;
8 if (index == items.size()) {
9 return 0;
10 }
11 var item = items.get(index);
12 int leave = recursive(index + 1, capacity);
13 if (item.weight() > capacity) {
14 return leave;
15 }
16 int take = item.value() + recursive(index + 1, capacity - item.weight());
17 return Math.max(leave, take);
18}
19
20// The same, but we remember the problems we have already solved (memoization)
21public int memoized(int capacity) {
22 return memoized(0, capacity, new HashMap<>());
23}
24
25private int memoized(int index, int capacity, Map<Subproblem, Integer> cache) {
26 calls++;
27 if (index == items.size()) {
28 return 0;
29 }
30 var subproblem = new Subproblem(index, capacity);
31 if (cache.containsKey(subproblem)) {
32 return cache.get(subproblem);
33 }
34 var item = items.get(index);
35 int leave = memoized(index + 1, capacity, cache);
36 int best = leave;
37 if (item.weight() <= capacity) {
38 int take = item.value() + memoized(index + 1, capacity - item.weight(), cache);
39 best = Math.max(leave, take);
40 }
41 cache.put(subproblem, best);
42 return best;
43}
The bottom-up version fills the table row by row, starting from the last item:
1// The cell table[index][c] is the best value we can get from the items from
2// this index on, with the capacity c. We fill the table from the last item.
3public int[][] table(int capacity) {
4 var table = new int[items.size() + 1][capacity + 1];
5 for (int index = items.size() - 1; index >= 0; index--) {
6 var item = items.get(index);
7 for (int c = 0; c <= capacity; c++) {
8 int leave = table[index + 1][c];
9 if (item.weight() > c) {
10 table[index][c] = leave;
11 } else {
12 int take = item.value() + table[index + 1][c - item.weight()];
13 table[index][c] = Math.max(leave, take);
14 }
15 }
16 }
17 return table;
18}
2.5. When Does It Work?#
Dynamic programming pays off when a problem has two properties:
Optimal substructure. The best solution of the problem is built from the best solutions of smaller problems of the same kind. In the knapsack, what we do with the remaining items and the room left is itself the same problem, and its best answer is exactly what we need. (Bellman called this the principle of optimality.)
Overlapping subproblems. The same smaller problems come back many times, and there are only a few different ones, each described by a few numbers, such as an item and an amount of room, or an index in a sequence. When the subproblems never repeat, there is nothing to remember, and memoization does not help.
Problems with a natural order, such as texts, arrays or sequences of points, often have both. In the lab, you will apply dynamic programming to a text problem, the edit distance between two words (see Optimization).
