Kodewick
Start learning →
Dynamic programming48 / 50

Dynamic programming

Lesson 48 of 50 · Part 9 · Algorithm design · about 17 minutes

Dynamic programming (DP) works each small problem out once and keeps it in a table: naive recursion makes 1664079 calls for fib(30), memoization cuts that to 57, and bottom-up dp[i] = dp[i - 1] + dp[i - 2] fills the table from small to large.

The Fibonacci numbers 1, 1, 2, 3, 5, 8, …: each is the sum of the two before. A recursion straight from the definition is three lines long; but working out fib(30) calls that function 1664079 times, and fib(50) over 25 billion times, minutes of running. Yet fib(50) needs only 48 additions. The difference: the recursion works out the same small problems thousands of times over. Writing down what's been worked out and never working it out again is where dynamic programming (DP) starts.

Naive recursion: the same problem many times over

In the figure, the arrows down are calls, and the 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.c
1#include <stdio.h>2 3long calls = 0;4 5int fib(int n) {6    calls++;7    if (n <= 2) return 1;8    return fib(n - 1) + fib(n - 2);9}10 11int main(void) {12    for (int n = 5; n <= 25; n += 5) {13        calls = 0;14        int r = fib(n);15        printf("fib(%d) = %d, %ld calls\n", n, r, calls);16    }17    // any bigger is too slow to run, so count the calls with a recurrence: C(n) = C(n - 1) + C(n - 2) + 118    long long c[51];19    c[1] = c[2] = 1;20    for (int n = 3; n <= 50; n++) c[n] = c[n - 1] + c[n - 2] + 1;21    printf("fib(30) takes %lld calls, fib(50) takes %lld calls\n", c[30], c[50]);22    return 0;23}
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) takes 1664079 calls, fib(50) takes 25172538049 calls

Each time n goes up by 5, the calls go up about 11 times. 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 <stdio.h>2 3int calls = 0;4 5int fib(int n) {6    calls++;7    if (n <= 2) return 1;8    return fib(n - 1) + fib(n - 2);9}10 11int main(void) {12    fib(6);13    printf("%d\n", calls);14    return 0;15}
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: write down what's been worked out

Add an array memo: once fib(n) is worked out, store it in memo[n]; next time it's wanted, look in the table first. This is memoization: the recursion looks the same, it just stops repeating itself.

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.c
1#include <stdio.h>2 3long calls = 0;4long long memo[100];                   // 0 means not worked out yet5 6long long fib(int n) {7    calls++;8    if (n <= 2) return 1;9    if (memo[n] != 0) return memo[n];  // already worked out: look it up10    memo[n] = fib(n - 1) + fib(n - 2);11    return memo[n];12}13 14int main(void) {15    long long r = fib(30);16    printf("fib(30) = %lld, %ld calls\n", r, calls);17    calls = 0;18    r = fib(90);19    printf("fib(90) = %lld, %ld more calls\n", r, calls);20    return 0;21}
Output
fib(30) = 832040, 57 calls
fib(90) = 2880067194370816120, 121 more calls

fib(30) now takes 57 calls. Working out fib(90) next, everything up to 30 is in the table already, and it takes only a hundred or so more. Each fib(k) is really worked out once: O(n) in all.

Guess the outputA wrong guess is fine

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

1#include <stdio.h>2 3int calls = 0;4int memo[20];5 6int fib(int n) {7    calls++;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(void) {15    fib(6);16    printf("%d\n", calls);17    return 0;18}
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 <stdio.h>2 3long long memo[100];4 5long long fib(int n) {6    if (n <= 2) return 1;7    if (memo[n]  0) return memo[n];8    memo[n] = fib(n - 1) + fib(n - 2);9    return memo[n];10}11 12int main(void) {13    printf("%lld\n", fib(40));14    return 0;15}

Bottom-up: fill the table from small to large

Memoization asks from the big problem downward; it can also go the other way: start from the smallest problems and work up in order, each one using only ones already done. That's what's usually called "filling the table", 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 the whole table isn't even needed: two variables rolling forward, and the space is O(1).

WayTimeSpaceWhat it's like
Naive recursionO(1.618ⁿ)O(n) (recursion depth)Easy to write, repeats itself
MemoizationO(n)O(n)Recursion + a table, 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
Choose one

Working out fib(n) with two rolling variables, what are the time and the space?

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's either 1 step up from step n − 1, or 2 steps up from step n − 2. Those two kinds of climb don't overlap, and together they're all of them. To write a DP, get these four steps clear:

StepThe question it answersClimbing stairs
1. StateWhat dp[i] stands forThe number of ways to reach step i
2. TransitionHow dp[i] comes from smaller onesdp[i] = dp[i − 1] + dp[i − 2]
3. Initial valuesWhat the smallest few aredp[1] = 1, dp[2] = 2
4. Order of fillingWhat comes first, so what's needed is readyi from 3 to n, small to large

Step 1 is the hardest and matters most: get the state right and the transition is often plain to see.

main.c
1#include <stdio.h>2 3int main(void) {4    int n = 45;5    long long dp[50];6    dp[1] = 1;                          // initial values7    dp[2] = 2;8    for (int i = 3; i <= n; i++)        // order of filling: small to large9        dp[i] = dp[i - 1] + dp[i - 2];  // the transition10    for (int i = 1; i <= 10; i++) printf("%lld ", dp[i]);11    printf("\n45 steps: %lld ways\n", dp[n]);12 13    long long a = 1, b = 2;             // rolling variables: just the last two14    for (int i = 3; i <= n; i++) {15        long long c = a + b;16        a = b;17        b = c;18    }19    printf("with rolling variables: %lld\n", b);20    return 0;21}
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 along by one. DP works when two things hold: a big problem's answer is worked out from smaller problems' answers (optimal substructure), and the smaller problems are needed again and again (overlapping subproblems). Last lesson's divide and conquer also builds on smaller answers, but its smaller problems don't depend on each other and never repeat, so nothing needs remembering.

Guess the outputA wrong guess is fine

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

1#include <stdio.h>2 3int main(void) {4    int dp[10];5    dp[0] = 1;6    dp[1] = 1;7    dp[2] = 2;8    for (int i = 3; i <= 5; i++)9        dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];10    printf("%d\n", dp[5]);11    return 0;12}

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 on step i costs cost[i]; you can start on step 0 or step 1, climb 1 or 2 at a time, and the top is step n (free). What's the least it can cost? dp[i] is the least paid in all before arriving at step i.

It should print
15 6
exercise1.c
1#include <stdio.h>2 3int min_cost(int cost[], int n) {4    int dp[100];5    dp[0] = 0;6    dp[1] = 0;7    // i from 2 to n: coming from i - 1 pays cost[i - 1], from i - 2 pays cost[i - 2]; take the smaller8    return dp[n];9}10 11int main(void) {12    int a[] = {10, 15, 20};13    int b[] = {1, 100, 1, 1, 1, 100, 1, 1, 100, 1};14    printf("%d %d\n", min_cost(a, 3), min_cost(b, 10));15    return 0;16}
Output
Press Run or Ctrl+Enter
Exercise 2

Fewest coins (the one greedy got wrong)

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

It should print
2 3 25
exercise2.c
1#include <stdio.h>2 3int coins[] = {1, 3, 4}, k = 3;4 5int fewest(int amount) {6    int dp[1000];7    dp[0] = 0;8    // a from 1 to amount: start dp[a] very large; for each coins[j] <= a, try dp[a - coins[j]] + 19    return dp[amount];10}11 12int main(void) {13    printf("%d %d %d\n", fewest(6), fewest(10), fewest(100));14    return 0;15}
Output
Press Run or Ctrl+Enter

Summary

Take-away

Dynamic programming: each small problem worked out once

  • Naive recursion: fib(30) makes 1664079 calls; with memoization, 57
  • Memoization: recursion + a table; bottom-up: fill the table small to large
  • Four steps: state, transition, initial values, order of filling
  • DP fits when there's optimal substructure + overlapping subproblems
1dp[1] = 1; dp[2] = 2;2for (int i = 3; i <= n; i++)3    dp[i] = dp[i - 1] + dp[i - 2];