Kodewick
Start learning →
Dynamic programming50 / 52

Dynamic programming

Lesson 50 of 52 · Part 9 · Algorithm design · about 24 minutes

Dynamic programming stores each small answer so it is never computed twice: naive recursion makes 1664079 calls for fib(30), a memo in a vector cuts that to a few dozen, and filling a table from small to large is DP.

The Fibonacci numbers 1, 1, 2, 3, 5, 8, … each are the sum of the two before. Write the recursion straight from the definition and it takes three lines; but fib(30) calls the function 1664079 times, and fib(50) more than 25 billion times, which takes minutes. Yet fib(50) needs only 48 additions. The difference: the recursion works out the same small problem thousands of times. Keeping what has been worked out and never working it out again is where dynamic programming (DP) starts.

Naive recursion: the same problem, many times

In the picture, arrows down are calls and dashed arrows up are returns.

fib(5)
1int fib(int n) {2    calls++;3    if (n <= 2) return 1;4    return fib(n - 1) + fib(n - 2);5}

The recursion tree of fib(5): fib(3) is worked out twice, fib(2) three times
main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5long long calls = 0;6 7int fib(int n) {8    calls++;9    if (n <= 2) return 1;10    return fib(n - 1) + fib(n - 2);11}12 13int main() {14    for (int n = 5; n <= 25; n += 5) {15        calls = 0;16        int r = fib(n);17        cout << "fib(" << n << ") = " << r << ", " << calls << " calls\n";18    }19    // Any bigger is too slow; count the calls with a recurrence: C(n) = C(n - 1) + C(n - 2) + 120    vector<long long> c(51);21    c[1] = c[2] = 1;22    for (int n = 3; n <= 50; n++) c[n] = c[n - 1] + c[n - 2] + 1;23    cout << "fib(30) needs " << c[30] << " calls, fib(50) needs " << c[50] << " calls\n";24    return 0;25}
Output
fib(5) = 5, 9 calls
fib(10) = 55, 109 calls
fib(15) = 610, 1219 calls
fib(20) = 6765, 13529 calls
fib(25) = 75025, 150049 calls
fib(30) needs 1664079 calls, fib(50) needs 25172538049 calls

Each time n goes up by 5, the calls multiply by about 11. The number of calls is exactly 2 × fib(n) − 1, and fib(n) itself grows like 1.618ⁿ: exponential.

Guess the outputA wrong guess is fine

How many times in all is fib called for fib(6)?

1#include <iostream>2using namespace std;3 4int calls = 0;5 6int fib(int n) {7    calls++;8    if (n <= 2) return 1;9    return fib(n - 1) + fib(n - 2);10}11 12int main() {13    fib(6);14    cout << calls << "\n";15    return 0;16}
Choose one

With naive recursion for fib(n), each time n goes up by 1, the number of calls is multiplied by roughly what?

Memoization: keep what you've worked out

Add a vector<long long> memo: once fib(n) is worked out, store it in memo[n]; next time, look in the table first. This is memoization: the recursion looks the same, it just stops repeating itself. vector<long long> memo(100) starts all 0, so 0 can mean "not worked out yet" (fib is never 0).

fib(5)
1long long fib(int n) {2    if (n <= 2) return 1;3    if (memo[n] != 0) return memo[n];4    memo[n] = fib(n - 1) + fib(n - 2);5    return memo[n];6}

fib(5) with memoization: the second time fib(3) is needed, it comes straight from the table, with no more calls below it
main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5long long calls = 0;6vector<long long> memo(100);           // all 0: 0 means not worked out yet7 8long long fib(int n) {9    calls++;10    if (n <= 2) return 1;11    if (memo[n] != 0) return memo[n];  // already known: look it up12    memo[n] = fib(n - 1) + fib(n - 2);13    return memo[n];14}15 16int main() {17    long long r = fib(30);18    cout << "fib(30) = " << r << ", " << calls << " calls\n";19    calls = 0;20    r = fib(90);21    cout << "fib(90) = " << r << ", " << calls << " more calls\n";22    return 0;23}
Output
fib(30) = 832040, 57 calls
fib(90) = 2880067194370816120, 121 more calls

fib(30) makes just 57 calls. Working out fib(90) next, everything up to 30 is already in the table, and it takes only a hundred or so more. Each fib(k) is really worked out once: O(n) in all. fib(90) is far past an int's range (about 2.1 billion), which is why this uses long long.

Guess the outputA wrong guess is fine

With memoization, how many times in all is fib called for fib(6)?

1#include <iostream>2#include <vector>3using namespace std;4 5int calls = 0;6vector<int> memo(20);7 8int fib(int n) {9    calls++;10    if (n <= 2) return 1;11    if (memo[n] != 0) return memo[n];12    memo[n] = fib(n - 1) + fib(n - 2);13    return memo[n];14}15 16int main() {17    fib(6);18    cout << calls << "\n";19    return 0;20}
Fill inTap one to fill a blank; tap a blank to take it back

Fill in the comparison for the table lookup: if the table doesn't hold 0, it has been worked out already, so return it at once. The program should print fib(40).

1#include <iostream>2#include <vector>3using namespace std;4 5vector<long long> memo(100);6 7long long fib(int n) {8    if (n <= 2) return 1;9    if (memo[n]  0) return memo[n];10    memo[n] = fib(n - 1) + fib(n - 2);11    return memo[n];12}13 14int main() {15    cout << fib(40) << "\n";16    return 0;17}

Bottom-up: fill the table from small to large

Memoization asks from the big problem downwards; you can also turn it around, start from the smallest problems and work up in order, each using only ones already done. That's what "filling the table" means, and it needs no recursion.

12345678910dp11        

fib bottom-up: dp[i] = dp[i − 1] + dp[i − 2], each box reading just the two to its left

Each box uses only the two before it, so you don't even need the whole table: two variables rolling forward, O(1) space.

WayTimeSpaceNotes
Naive recursionO(1.618ⁿ)O(n) (recursion depth)Easy to write, repeats itself
MemoizationO(n)O(n)Recursion + lookup, works out only what's needed
Bottom-up tableO(n)O(n)A loop, no recursion overhead
Rolling variablesO(n)O(1)Keeps only what the next step needs
Choose one

A different recurrence: dp[1] = 1, dp[2] = 1, dp[i] = dp[i − 1] + 2 × dp[i − 2]. Filling the table from small to large, what is dp[6]?

Put in orderDrag, or use the arrows

Work out fib(10) with two rolling variables: a and b are the latest two terms. Put the three lines of the loop in order.

  1. a = b;
  2. long long c = a + b;
  3. b = c;
Should print
55

Climbing stairs: the four steps of DP

A staircase has n steps and you climb 1 or 2 at a time. How many ways are there to the top?

Think about the last move: it is either 1 step from step n − 1 or 2 steps from step n − 2. Those two kinds don't overlap, and together they are all of them. To write a DP, think these four steps through:

StepThe questionClimbing stairs
1. StateWhat does dp[i] meanThe number of ways to reach step i
2. TransitionHow is dp[i] made from smaller onesdp[i] = dp[i − 1] + dp[i − 2]
3. Initial valuesWhat are the smallest fewdp[1] = 1, dp[2] = 2
4. OrderWhat goes first, so everything needed is readyi from 3 to n, small to large

Step 1 is the hardest and matters most: once the state is right, the transition often follows at a glance. In C++ the table is vector<long long> dp(n + 1): its size can be known only at run time, indexes 0 to n are exactly n + 1 boxes, and they start at 0.

main.cpp
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    int n = 45;7    vector<long long> dp(n + 1);        // indexes 0 to n, all 08    dp[1] = 1;                          // initial values9    dp[2] = 2;10    for (int i = 3; i <= n; i++)        // order: small to large11        dp[i] = dp[i - 1] + dp[i - 2];  // transition12    for (int i = 1; i <= 10; i++) cout << dp[i] << " ";13    cout << "\n45 steps: " << dp[n] << " ways\n";14 15    long long a = 1, b = 2;             // rolling variables: keep just the last two16    for (int i = 3; i <= n; i++) {17        long long c = a + b;18        a = b;19        b = c;20    }21    cout << "With rolling variables: " << b << "\n";22    return 0;23}
Output
1 2 3 5 8 13 21 34 55 89 
45 steps: 1836311903 ways
With rolling variables: 1836311903

It's the Fibonacci numbers shifted by one. DP works thanks to two things: the answer to the big problem is made from answers to smaller ones (optimal substructure), and the smaller problems are used again and again (overlapping subproblems). Divide and conquer, at the start of this chapter, also builds on smaller answers, but its parts are independent and never repeat, so there's nothing to remember.

Guess the outputA wrong guess is fine

Climbing 1, 2 or 3 steps at a time, how many ways are there up 5 steps?

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> dp(6);7    dp[0] = 1;8    dp[1] = 1;9    dp[2] = 2;10    for (int i = 3; i <= 5; i++)11        dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];12    cout << dp[5] << "\n";13    return 0;14}

In exams: DP mostly comes up in algorithm design questions, usually asking you to "give the state, the transition, the boundary conditions, and the time and space complexity": exactly these four steps. The first interview question is very often climbing stairs or a variation on it (each step has a cost, some steps can't be used).

Choose one

Climbing stairs (1 or 2 steps at a time) with other starting values: dp[0] = 1 (standing on the ground counts as one way), dp[1] = 1, dp[i] = dp[i − 1] + dp[i − 2]. What is dp[4]?

Choose one

Merge sort also builds the big answer out of smaller problems' answers. Why doesn't it need memoization?

Exercise 1

Climbing stairs with costs

Stepping onto step i costs cost[i]. You may start on step 0 or step 1, climb 1 or 2 steps at a time, and reach step n (the top, free). What is the least it can cost? dp[i] is the least paid in total before standing on step i.

It should print
15 6
exercise1.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int min_cost(const vector<int>& cost) {7    int n = cost.size();8    vector<int> dp(n + 1);9    dp[0] = 0;10    dp[1] = 0;11    // i from 2 to n: coming from i - 1 costs cost[i - 1], from i - 2 costs cost[i - 2]; take the smaller12    return dp[n];13}14 15int main() {16    vector<int> a = {10, 15, 20};17    vector<int> b = {1, 100, 1, 1, 1, 100, 1, 1, 100, 1};18    cout << min_cost(a) << " " << min_cost(b) << "\n";19    return 0;20}
Output
Press Run or Ctrl+Enter
Exercise 2

Fewest coins (the one greedy got wrong)

With coins 1, 3 and 4, what is the fewest coins that make amount? In the greedy lesson, greedy made 6 with 3 coins. dp[a] is the fewest coins for a: if the last coin is c, that's dp[a − c] + 1; take the smallest over every c.

It should print
2 3 25
exercise2.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6vector<int> coins = {1, 3, 4};7 8int fewest(int amount) {9    vector<int> dp(amount + 1);10    dp[0] = 0;11    // a from 1 to amount: set dp[a] very large first; for each c <= a, try dp[a - c] + 112    return dp[amount];13}14 15int main() {16    cout << fewest(6) << " " << fewest(10) << " " << fewest(100) << "\n";17    return 0;18}
Output
Press Run or Ctrl+Enter

With the STL

The programs in the earlier stages already use the STL: the table is vector<long long> dp(n + 1) and the memo is vector<long long> memo(100). A vector is one contiguous array, so dp[i] is O(1), as fast as a C array; on top of that its size can be set at run time, and it frees itself when the function ends.

But the memo can't always be a vector. When the state can take a huge range of values but only a few are ever used, you can't make an array that big; then use a map (a red-black tree, O(log m) per lookup, m being how many are stored) or an unordered_map (a hash table, O(1) on average). For example f(0) = 1, f(n) = f(n / 2) + f(n / 3) (integer division); find f(10¹²): 10¹² boxes is impossible, yet only a few hundred values of n are ever used.

main.cpp
1#include <iostream>2#include <map>3using namespace std;4 5map<long long, long long> memo;6long long calls = 0;7 8long long f(long long n) {9    calls++;10    if (n == 0) return 1;11    auto it = memo.find(n);            // one lookup: if found, use it12    if (it != memo.end()) return it->second;13    long long r = f(n / 2) + f(n / 3);14    memo[n] = r;15    return r;16}17 18int main() {19    long long n = 1000000000000LL;20    cout << "f(10^12) = " << f(n) << "\n";21    cout << "The memo holds " << memo.size() << ", with " << calls << " calls\n";22    cout << "Smallest key " << memo.begin()->first << ", largest key " << memo.rbegin()->first << "\n";23    return 0;24}
Output
f(10^12) = 4266563557
The memo holds 437, with 875 calls
Smallest key 1, largest key 1000000000000

Out of a range of 10¹², only a few hundred states are used. There's a trap in the lookup: memo[n] inserts a 0 when n isn't there, then returns it. Writing if (memo[n] != 0) happens to give the right answer, but every miss stuffs an empty entry into the map; to ask "is it there?" use find or count. A map keeps its keys sorted, so it can be printed in order; an unordered_map has no fixed order, so to print one, look up each key.

MemoOne lookupWhen
vector<long long> memo(n + 1, -1)O(1)The state is an integer 0 to n and most get used
vector<vector<long long>>O(1)Two integer parameters, both in a small range
map<long long, long long>O(log m)A huge range, few used; the key can be a pair
unordered_map<long long, long long>O(1) on averageThe same, faster, but a pair can't be the key as is

If a vector will do, use a vector: for the same recursion, a vector lookup is one index, a map lookup walks log m levels of a red-black tree. Start it at −1 rather than 0, because in many problems the answer itself can be 0 (say, "the number of ways" when there are none).

In interviews: For a DP, say the four steps first: the state, the transition, the initial values, the order of filling; then write the code; then give the time and space. Climbing stairs and its variants (each step has a cost, some steps can't be used) are often the first question. Asked "memoization or a table, which is better": the same complexity; memoization works out only the states it needs and is easy to write, the table has no recursion overhead and is easier to squeeze in space. Exam algorithm design questions also ask to "give the state, the transition, the boundary conditions, and the time and space complexity": exactly these four steps.

Guess the outputA wrong guess is fine

m starts out empty. After reading m[5] once and asking m.count(7) once, what does the program print?

1#include <iostream>2#include <map>3using namespace std;4 5int main() {6    map<int, int> m;7    int a = m[5];8    int b = m.count(7);9    cout << a << " " << b << " " << m.size() << "\n";10    return 0;11}

Summary

Take-away

Dynamic programming: each small problem worked out once

  • Naive recursion makes 1664079 calls for fib(30); with memoization, 57
  • Memoization: recursion + lookup; bottom-up: fill the table small to large
  • Four steps: state, transition, initial values, order of filling
  • DP works with optimal substructure + overlapping subproblems
  • The memo: a vector if it will do; a map for huge ranges, and find to ask if it's there
1vector<long long> dp(n + 1);2dp[1] = 1; dp[2] = 2;3for (int i = 3; i <= n; i++)4    dp[i] = dp[i - 1] + dp[i - 2];