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:

Java Fibonacci and knapsack

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:

Listing 2.25 The Fibonacci numbers, from the definition (pseudocode)#
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.

../../_images/fib_tree.svg

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).

Listing 2.26 The Fibonacci numbers, with memoization (pseudocode)#
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.

../../_images/fib_memo.svg

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.

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.

../../_images/fib_table.svg

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.#

Listing 2.27 The Fibonacci numbers, bottom-up (pseudocode)#
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.

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:

Listing 2.28 The best value in the box, with recursion (pseudocode)#
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.

../../_images/knapsack_states.svg

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.

../../_images/knapsack_table.svg

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.

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).