Spot repeated subproblems, then cache them or fill a table in the right order.
You work on a fitness app with a stair challenge. A building has a staircase, and a user climbs one or two stairs at a time. Your team lead says: "For any staircase, how many different ways can a user climb it?"
Count by hand first. Write ways(n) for the number of ways to climb n stairs.
| Stairs | Ways | Which ways |
|---|---|---|
| 0 | 1 | Stay where you are: one way to do nothing |
| 1 | 1 | One move of one stair |
| 2 | 2 | 1 + 1, or 2 |
| 3 | 3 | 1 + 1 + 1, 1 + 2, or 2 + 1 |
| 4 | 5 | 1 + 1 + 1 + 1, 1 + 1 + 2, 1 + 2 + 1, 2 + 1 + 1, or 2 + 2 |
Look at the last move of each way for 4 stairs. Three ways end with + 1: 1 + 1 + 1, 1 + 2 and 2 + 1 come first, which are exactly the 3 ways for 3 stairs. Two ways end with + 2: 1 + 1 and 2 come first, which are exactly the 2 ways for 2 stairs. So 4 stairs have 3 + 2 = 5 ways.
The same is true for every staircase. The last move onto stair n was either one stair, from stair n - 1, or two stairs, from stair n - 2. So ways(n) = ways(n - 1) + ways(n - 2), and each answer is the sum of the two before it. Five stairs have 5 + 3 = 8 ways.
The first attempt is correct. Turn the rule into a recursion, with ways(0) = 1 and ways(1) = 1 as the cases that need no rule.
def ways(n):
if n <= 1:
return 1
return ways(n - 1) + ways(n - 2)Now check the real size. Here is the tree of every call that ways(5) makes. Each call sits under the call that made it, and "again" marks a call whose question was already asked earlier in the tree.
ways(5)
├── ways(4)
│ ├── ways(3)
│ │ ├── ways(2)
│ │ │ ├── ways(1)
│ │ │ └── ways(0)
│ │ └── ways(1) again
│ └── ways(2) again
│ ├── ways(1) again
│ └── ways(0) again
└── ways(3) again
├── ways(2) again
│ ├── ways(1) again
│ └── ways(0) again
└── ways(1) againThe whole branch under the first ways(3) is worked out a second time on the right, under ways(5). Counted by question:
| Call | Times it is made |
|---|---|
ways(5) |
1 |
ways(4) |
1 |
ways(3) |
2 |
ways(2) |
3 |
ways(1) |
5 |
ways(0) |
3 |
That is 15 calls, for only 6 different questions: 0, 1, 2, 3, 4 and 5. Nine of the 15 calls repeat a call that was already made. Each repeat does all its work again, including every call under it.
You drew trees like this in the recursion lessons, where you added up the cost of a recursion tree. Here the tree shows something new: the same call appears many times.
The recursion for five stairs makes fifteen calls but asks only six different questions. Nine calls repeat an earlier call and do all its work again.
This grows quickly. Each extra stair multiplies the number of calls by about 1.6. For 40 stairs there are 165,580,141 ways, and the recursion makes 331,160,281 calls. At ten million calls a second that is more than 33 seconds for one answer, yet only 41 different questions exist: zero stairs up to forty.
A smaller question of the same kind, such as ways(3) inside ways(5), is a subproblem. When the same subproblems come up again and again, they overlap. That is the signal for dynamic programming: solve each subproblem once, and use its answer every time it comes up.
A cashier closing the till is asked for running totals. First the coins in trays 1 to 3, then in trays 1 to 4, then in trays 1 to 5. Counting from tray 1 every time would count the first trays again and again.
So she writes each total on a sticky note. For trays 1 to 4 she reads the note for trays 1 to 3 and counts only tray 4.
This is the idea behind dynamic programming. Each smaller total is a subproblem, and each note is its saved answer. Every bigger answer is built from a smaller one, and no tray is counted twice.
The picture hides one thing. A note needs a label, such as "trays 1 to 3", so she can find it. In code, the label is the state: the few numbers that say which smaller question this is. For the stairs, the state is the number of stairs.
A cashier writes each running total on a sticky note and builds the next one from it. Memoisation saves answers the same way, under the state.
Predict what happens
Q The recursion for five stairs makes 15 calls. How many different values of n appear in those calls?
Answer: B
The calls use only the values 0 to 5, which is 6 values. The other 9 calls repeat a value that was already asked. That repetition is what dynamic programming removes.
There are two ways to stop the repeats. They give the same answers, and they differ in where they start.
Keep a memo, a dictionary of saved answers. Before working out ways(k), look in the memo. If the answer is there, return it. Otherwise work it out, save it, and return it.
This is memoisation, or top down: you start from the question you want and recurse.
For ways(5) the tree shrinks from 15 calls to 9.
| Call | What happens |
|---|---|
ways(5), ways(4), ways(3), ways(2) |
New. Each makes two calls |
ways(1), ways(0) |
New base cases: 1 and 1, both saved. ways(2) is saved as 2 |
ways(1) under ways(3) |
In the memo: returns 1 at once. ways(3) is saved as 3 |
ways(2) under ways(4) |
In the memo: returns 2 at once. ways(4) is saved as 5 |
ways(3) under ways(5) |
In the memo: returns 3 at once. ways(5) is 8 |
Six calls worked something out, one for each different question. Three calls read the memo and stopped. The right branch under ways(5), which made five calls without a memo, is now a single call.
With a memo, a call whose answer is saved returns it at once. The tree for five stairs shrinks from fifteen calls to nine.
Step by step: Plain recursion on five stairs. The animated player loads in your browser.
Step by step: Recursion with a memo on five stairs. The animated player loads in your browser.
def ways_to_climb(n):
memo = {}
def ways(k):
# [1] If the answer for k is saved, read it and stop.
if k in memo:
return memo[k]
# [2] Otherwise work it out: zero stairs and one stair have one way, and any other k adds the two smaller answers.
memo[k] = 1 if k <= 1 else ways(k - 1) + ways(k - 2)
# [3] The answer was saved before it is returned, so the next call for k reads it.
return memo[k]
return ways(n)public int waysToClimb(int n) {
return ways(n, new java.util.HashMap<>());
}
private int ways(int k, java.util.Map<Integer, Integer> memo) {
// [1] If the answer for k is saved, read it and stop.
if (memo.containsKey(k)) return memo.get(k);
// [2] Otherwise work it out: zero stairs and one stair have one way, and any other k adds the two smaller answers.
int result = k <= 1 ? 1 : ways(k - 1, memo) + ways(k - 2, memo);
// [3] The answer was saved before it is returned, so the next call for k reads it.
memo.put(k, result);
return result;
}int waysFrom(int k, unordered_map<int, int>& memo) {
// [1] If the answer for k is saved, read it and stop.
if (memo.count(k)) return memo[k];
// [2] Otherwise work it out: zero stairs and one stair have one way, and any other k adds the two smaller answers.
int result = k <= 1 ? 1 : waysFrom(k - 1, memo) + waysFrom(k - 2, memo);
// [3] The answer was saved before it is returned, so the next call for k reads it.
memo[k] = result;
return result;
}
int waysToClimb(int n) {
unordered_map<int, int> memo;
return waysFrom(n, memo);
}function waysToClimb(n) {
const memo = new Map();
function ways(k) {
// [1] If the answer for k is saved, read it and stop.
if (memo.has(k)) return memo.get(k);
// [2] Otherwise work it out: zero stairs and one stair have one way, and any other k adds the two smaller answers.
const result = k <= 1 ? 1 : ways(k - 1) + ways(k - 2);
// [3] The answer was saved before it is returned, so the next call for k reads it.
memo.set(k, result);
return result;
}
return ways(n);
}Remove the recursion. Make a table with one cell for each question, and fill it from the cells you already know. This is tabulation, or bottom up: you start from the base cases and build towards the question.
For the stairs, cell k holds ways(k). Cells 0 and 1 hold 1. Every other cell adds the two cells before it, so fill from left to right.
| Cell | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Ways | 1 | 1 | 2 | 3 | 5 | 8 | 13 |
| How it was filled | base | base | 1 + 1 | 2 + 1 | 3 + 2 | 5 + 3 | 8 + 5 |
Seven cells, each filled once from two cells that were already filled. There is no recursion and no repeated work.
def ways_to_climb(n):
# [1] ways[k] is the number of ways to climb k stairs. Zero stairs and one stair each have one way.
ways = [0] * (n + 2)
ways[0] = 1
ways[1] = 1
for k in range(2, n + 1):
# [2] The last move was one stair or two, so add the two cells before this one.
ways[k] = ways[k - 1] + ways[k - 2]
# [3] The cell for n stairs is the answer. The loop fills the cells in order, so every cell it reads is ready.
return ways[n]public int waysToClimb(int n) {
// [1] ways[k] is the number of ways to climb k stairs. Zero stairs and one stair each have one way.
int[] ways = new int[n + 2];
ways[0] = 1;
ways[1] = 1;
for (int k = 2; k <= n; k++) {
// [2] The last move was one stair or two, so add the two cells before this one.
ways[k] = ways[k - 1] + ways[k - 2];
}
// [3] The cell for n stairs is the answer. The loop fills the cells in order, so every cell it reads is ready.
return ways[n];
}int waysToClimb(int n) {
// [1] ways[k] is the number of ways to climb k stairs. Zero stairs and one stair each have one way.
vector<int> ways(n + 2, 0);
ways[0] = 1;
ways[1] = 1;
for (int k = 2; k <= n; k++) {
// [2] The last move was one stair or two, so add the two cells before this one.
ways[k] = ways[k - 1] + ways[k - 2];
}
// [3] The cell for n stairs is the answer. The loop fills the cells in order, so every cell it reads is ready.
return ways[n];
}function waysToClimb(n) {
// [1] ways[k] is the number of ways to climb k stairs. Zero stairs and one stair each have one way.
const ways = new Array(n + 2).fill(0);
ways[0] = 1;
ways[1] = 1;
for (let k = 2; k <= n; k++) {
// [2] The last move was one stair or two, so add the two cells before this one.
ways[k] = ways[k - 1] + ways[k - 2];
}
// [3] The cell for n stairs is the answer. The loop fills the cells in order, so every cell it reads is ready.
return ways[n];
}A grid table is filled row by row, left to right, so the cell above and the cell to the left are ready. The finish holds ten routes.
Exercise · Put it in order: Fill the stairs table. Arrange the lines into a function that fills a table from the base cases and returns the number of ways to climb n stairs.
def ways_to_climb(n):
ways = [0] * (n + 2)
ways[0] = 1
ways[1] = 1
for k in range(2, n + 1):
ways[k] = ways[k - 1] + ways[k - 2]
return ways[n]
for k in range(n, 1, -1):
ways[0] = 0Step by step: A table for six stairs. The animated player loads in your browser.
A cell reads other cells, so those cells must be filled first. For the stairs this is easy: left to right. A second example shows why the order is a real decision.
You searched a grid in the BFS and DFS on a grid lesson. Here the grid is a table, and each block holds one number.
A driver moves right or down across a grid of blocks. Let routes[r][c] be the number of routes from the top left block to block (r, c). Every block can be reached from the block above it or the block to its left, so routes[r][c] = routes[r - 1][c] + routes[r][c - 1]. The start has 1 route.
| Column 0 | Column 1 | Column 2 | Column 3 | |
|---|---|---|---|---|
| Row 0 | 1 | 1 | 1 | 1 |
| Row 1 | 1 | 2 (1 + 1) | 3 (1 + 2) | 4 (1 + 3) |
| Row 2 | 1 | 3 (2 + 1) | 6 (3 + 3) | 10 (4 + 6) |
The first row and the first column have only one neighbour to read, so each cell there has 1 route. Every other cell adds its neighbour above and its neighbour on the left. The finish holds 10, so there are 10 routes.
Fill row by row, from the top, and left to right in each row. Then the cell above and the cell on the left are always filled before the cell that reads them. Fill the cell (1, 1) before (0, 1) and it would add an empty cell, and every number after it would be wrong. The table is only as correct as the order it was filled in.
Predict what happens
Q In the grid table, the cell for row 1, column 2 holds 3. Row 2, column 2 is filled next. Which cells does it add?
Answer: B
Each cell adds the cell above and the cell to its left. Both are already filled, because the table is filled row by row, left to right. The sum is 3 + 3 = 6.
Pick a problem, choose a method, then step through it forwards and back. In a table, the cells a new cell reads from are highlighted and joined to it by lines. For the stairs, the recursion tree marks calls that repeat, and calls that read the memo.
Try these four, in order:
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
Exercise · Break it: Find the grid where a closed block is ignored. A driver moves right or down across a grid. A 1 is a closed block and a 0 is open. This count sets the whole first row and first column to 1 and only checks closed blocks inside. The grid has at least one row and one column. Find a grid where it gives the wrong number of routes.
def routes(grid):
rows, cols = len(grid), len(grid[0])
table = [[1] * cols for _ in range(rows)]
for r in range(1, rows):
for c in range(1, cols):
if grid[r][c] == 1:
table[r][c] = 0
else:
table[r][c] = table[r - 1][c] + table[r][c - 1]
return table[rows - 1][cols - 1]Every dynamic programming solution has the same three parts. Write them in words before you write any code.
k stairs". If you cannot say it in one sentence, the table will go wrong.After each cell is filled, it holds the answer to its own smaller question, because every cell it reads was already filled and already correct.
Why does the table give the right answer? The base cells are right by definition. Each new cell is worked out from cells that are already right, with a rule that is true for its own question.
So every cell is right, one after another, up to the cell you want. The memo works the same way, except that the recursion decides the order.
The Greedy choices lesson showed a rule that fails. A shop has coins worth 1, 3 and 4 and must give change of 6 with the fewest coins. Biggest coin first takes 4, then 1 and 1: three coins. But 3 and 3 is two coins.
A table does not guess. Its state is: "the fewest coins that make exactly a". The base case is that 0 coins make 0. For every amount, try each coin that fits, look up the cell for what is left, and keep the smallest: fewest[a] = 1 + min(fewest[a - coin]).
Each cell reads cells to its left, so fill from left to right.
| Amount | Coin 1 leaves | Coin 3 leaves | Coin 4 leaves | Fewest coins |
|---|---|---|---|---|
| 0 | 0 (base case) | |||
| 1 | 0: 0 + 1 = 1 | 1 | ||
| 2 | 1: 1 + 1 = 2 | 2 | ||
| 3 | 2: 2 + 1 = 3 | 0: 0 + 1 = 1 | 1 | |
| 4 | 3: 1 + 1 = 2 | 1: 1 + 1 = 2 | 0: 0 + 1 = 1 | 1 |
| 5 | 4: 1 + 1 = 2 | 2: 2 + 1 = 3 | 1: 1 + 1 = 2 | 2 |
| 6 | 5: 2 + 1 = 3 | 3: 1 + 1 = 2 | 2: 2 + 1 = 3 | 2 |
Amount 6 needs 2 coins, which greedy missed. The table looked at every coin, so no counterexample can fool it. An amount that no coin can reach gets "cannot be made", written as infinity, and never 0.
For coins worth one, three and four, the table finds two coins for six by trying every coin at every amount. Biggest coin first uses three.
Predict what happens
Q For the coins 1, 3 and 4, the table holds 2 for amount 5 and 1 for amount 3. What does the cell for amount 6 take from the coin 3?
Answer: B
The coin 3 leaves 6 - 3 = 3, and the cell for amount 3 holds 1. One more coin makes 2. This is the cell the best answer reads: the coins 3 and 3.
Three kinds of question point to it.
| Kind of question | Example | The cell holds |
|---|---|---|
| Count the ways | How many ways to climb 5 stairs, or routes across a grid? | A number of ways |
| Best value | The fewest coins, the largest total tip, the cheapest climb | The best value so far |
| Can it be done | Can this amount be paid exactly, or this text split into known words? | True or false |
Then check two more things. There is a choice at every step, such as one stair or two, or which coin to use. And the same smaller question comes back again and again. If each smaller question appears only once, plain recursion is enough.
Each one has the same three parts. Read the state aloud: it is the key to the whole solution.
| Problem | The state: what one cell holds | Base case |
|---|---|---|
| Climbing stairs | The number of ways to climb k stairs |
1 way for 0 and for 1 stair |
| Picking non-adjacent deliveries | The largest total tip from the first i orders |
0 for no orders |
| Coin change | The fewest coins that make exactly a |
0 coins for the amount 0 |
| Routes on a grid | The number of routes to block (r, c) |
1 route to the start |
| Common letters of two words | The longest common subsequence of the first i letters of one word and the first j of the other |
0 when either side has no letters |
The last one is a preview. A search box can rank suggestions by how many letters of what you typed appear in the suggestion, in the same order. Compare sale with seal.
The state: a cell holds the most letters that appear, in the same order, in the first i letters of sale and the first j letters of seal. Letters in between may be skipped, so the shared letters need not sit side by side.
The table has one row for each letter of sale and one column for each letter of seal. A match adds 1 to the cell diagonally up and to the left. A mismatch takes the larger of the cell above and the cell to the left.
| (none) | s | e | a | l | |
|---|---|---|---|---|---|
| (none) | 0 | 0 | 0 | 0 | 0 |
| s | 0 | 1 (s matches s) | 1 | 1 | 1 |
| a | 0 | 1 | 1 | 2 (a matches a) | 2 |
| l | 0 | 1 | 1 | 2 | 3 (l matches l) |
| e | 0 | 1 | 2 (e matches e) | 2 | 3 |
Every cell without a note is a mismatch. Take row e, column a: the letters differ, so the cell takes the larger of the cell above (2) and the cell on its left (2). Row s carries its 1 to the right the same way.
The bottom right cell is 3: the letters s, a, l, in that order, appear in both words. This is the longest common subsequence. Diff tools use the same idea, and the last warm-up problem builds it.
Exercise · Predict the output: How many letters do the two words share?. The search box compares the words plate and pleat with the same table. The program prints the bottom right cell. What does it print?
a = "plate"
b = "pleat"
table = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
table[i][j] = table[i - 1][j - 1] + 1
else:
table[i][j] = max(table[i - 1][j], table[i][j - 1])
print(table[len(a)][len(b)])A table can be large, but each cell often reads only a few cells close behind it. Then you can forget the rest. For the stairs, a cell reads the two cells before it, so two numbers are enough.
def ways_to_climb(n):
# [1] Only the last two answers are ever read, so keep two numbers.
two_back, one_back = 1, 1
for k in range(2, n + 1):
# [2] The new answer is their sum. Then slide the pair along by one stair.
two_back, one_back = one_back, two_back + one_back
# [3] The newest number is the answer for n stairs. Zero and one stair give 1.
return one_backpublic int waysToClimb(int n) {
// [1] Only the last two answers are ever read, so keep two numbers.
int twoBack = 1;
int oneBack = 1;
for (int k = 2; k <= n; k++) {
// [2] The new answer is their sum. Then slide the pair along by one stair.
int next = twoBack + oneBack;
twoBack = oneBack;
oneBack = next;
}
// [3] The newest number is the answer for n stairs. Zero and one stair give 1.
return oneBack;
}int waysToClimb(int n) {
// [1] Only the last two answers are ever read, so keep two numbers.
int twoBack = 1;
int oneBack = 1;
for (int k = 2; k <= n; k++) {
// [2] The new answer is their sum. Then slide the pair along by one stair.
int next = twoBack + oneBack;
twoBack = oneBack;
oneBack = next;
}
// [3] The newest number is the answer for n stairs. Zero and one stair give 1.
return oneBack;
}function waysToClimb(n) {
// [1] Only the last two answers are ever read, so keep two numbers.
let twoBack = 1;
let oneBack = 1;
for (let k = 2; k <= n; k++) {
// [2] The new answer is their sum. Then slide the pair along by one stair.
const next = twoBack + oneBack;
twoBack = oneBack;
oneBack = next;
}
// [3] The newest number is the answer for n stairs. Zero and one stair give 1.
return oneBack;
}The same idea has a different size in each problem. A grid cell reads the cell above and the cell on its left.
Keep one row and overwrite it from left to right. Before a cell is overwritten, it still holds the value from the row above. The cell on its left already holds its new value. So one row of numbers is enough.
Exercise · Find the bug: The row that reads the wrong cell. This code counts the routes across a grid of rows by cols blocks, keeping only one row. It returns too few routes on some grids. Which line is wrong?
def routes(rows, cols):
row = [1] * cols
for r in range(1, rows):
for c in range(cols - 1, 0, -1):
row[c] = row[c] + row[c - 1]
return row[cols - 1]A common letters cell also reads the cell diagonally up and to the left, and the one-row overwrite has already replaced that value. So keep two rows: the row above and the row being filled. For two words of 1,000 letters, that is about 2,000 numbers instead of a million.
Coin change reads cells as far back as the largest coin, so it keeps that many cells.
Keep the whole table when you need to read the answer back, such as which coins were used. Keep only the last row when you need only the number.
Predict what happens
Q In coin change, what does the cell for amount 6 hold?
Answer: B
The state is the plain sentence that says what a cell holds. Here a cell holds the fewest coins that make exactly that amount. Any other meaning would make the rule that fills the table wrong.
Now write it yourself. The lab has one function, fewest_coins(coins, amount). It returns the fewest coins that make exactly amount, using any coin as often as you like, or -1 when the amount cannot be made.
Here is a small run with coins 2 and 5 and an amount of 7. The table has cells 0 to 7.
| Amount | Coin 2 leaves | Coin 5 leaves | Fewest coins |
|---|---|---|---|
| 0 | 0 (base case) | ||
| 1 | none fits | none fits | cannot be made |
| 2 | 0: 0 + 1 = 1 | 1 | |
| 3 | 1: cannot be made | cannot be made | |
| 4 | 2: 1 + 1 = 2 | 2 | |
| 5 | 3: cannot be made | 0: 0 + 1 = 1 | 1 |
| 6 | 4: 2 + 1 = 3 | 1: cannot be made | 3 |
| 7 | 5: 1 + 1 = 2 | 2: 1 + 1 = 2 | 2 |
The answer for 7 is 2, which is 5 and 2. If the last cell had been "cannot be made", the function would return -1.
Three rules keep it correct:
a". Say it before you write the loop.0 for the amount 0 and "cannot be made" for every other cell, never 0.a, and skip a coin whose leftover cell is "cannot be made".Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
The cost of a table is the number of states times the work for each state.
| Question | Plain recursion | Memo or table |
|---|---|---|
| Time to work out the answer | About 1.6 times more calls with every extra stair | O(n): n + 1 states, each reading 2 cells |
| Steps for 40 stairs | 331,160,281 calls | At most 82 reads |
| Memory | O(n): the depth of the calls | O(n) for the memo or the table, or O(1) with two numbers. The memo also recurses n calls deep |
| Why the answer is right | Every smaller question is asked again | Each question is worked out once, in an order that has its inputs ready |
The same count works for every problem. Multiply the number of states by the cells each one reads.
| Problem | States | Reads for each state | Time |
|---|---|---|---|
Climbing n stairs |
n + 1 |
2 | O(n) |
Fewest coins for amount A, with k coins |
A + 1 |
up to k |
O(A × k) |
Routes on an R by C grid |
R × C |
2 | O(R × C) |
Common letters of words of n and m letters |
(n + 1) × (m + 1) |
1 or 2 | O(n × m) |
For A = 10,000 and 12 coins, that is about 120,000 steps. For two words of 1,000 letters it is about a million. A recursion that tries every choice cannot finish on either.
Both work out each state once, so for the stairs both take about the same number of steps. They differ in three ways.
ways(n) waits for ways(n - 1), which waits for ways(n - 2), down to 0, so about n calls are open at once. Python stops at about 1,000 nested calls by default, so the memo version of ways_to_climb(1000) fails with RecursionError, while the table returns at once. JavaScript and Java allow more, roughly 5,000 to 20,000 on default settings, but a deep enough input still overflows the stack, and the table has no such limit.Start with the memo when the recursion is the clearest way to think about a problem. Turn it into a table when the input is deep, as in the warm-up problem with 100,000 stairs, or when speed matters.
Use dynamic programming when three things are true. There is a choice at every step. The answer is built from answers to smaller questions of the same kind. And the same smaller question comes back many times, while the number of different questions stays small.
Words such as "how many ways", "the fewest", "the largest total" and "can it be done" are a hint. Draw the recursion tree for a small input. If calls with the same arguments repeat, save them.
Do not use it when each smaller question appears only once. Merge sort splits a list into two halves that never overlap, so plain recursion is enough.
Do not use it when a greedy rule is provably safe, such as choosing the most talks in one room. Greedy is simpler and faster.
Do not use it when the state is too big to store, such as "which subset of a long list has been used". Then the number of states grows as fast as the number of choices. Also, if you must list every answer rather than count or optimise, use backtracking.
ways[0] = 0 looks harmless, but zero stairs has one way: stay where you are. Then ways[2] = ways[1] + ways[0] = 1 + 0 = 1, not 2, and every later cell is wrong. The base case is the cell you know, not a zero by habit.
Starting the stairs table with zero ways for zero stairs makes two stairs get one way instead of two, and every later cell is wrong.
1 + min(best[a - c] for c in coins if c <= a) has nothing to take the minimum of when no coin fits. Writing min(..., default=0) makes an impossible amount look cheap.
With coins [2] and an amount of 3, the table says amount 1 needs 1 coin and amount 3 needs 2 coins, so the function returns 2. The answer is -1. Use infinity, and skip a leftover that is infinity.
memo[k] = ways(k - 1) + ways(k - 2) saves the answer, but without if k in memo: return memo[k] nothing reads it. The answer is right, and it still makes 331,160,281 calls for 40 stairs. Save the answer and look it up before recursing.
two_back = one_back followed by one_back = two_back + one_back adds the new two_back to itself. It gives 2 for two stairs, which is right by luck, and 4 for three stairs. The answer for three stairs is 3. Use the old values together: two_back, one_back = one_back, two_back + one_back.
for k in range(n, 1, -1) fills the table from the top. For five stairs, cell 5 is filled first and reads cells 4 and 3, which are still 0, so it holds 0 and the function returns 0. The answer is 8. Fill left to right, so every cell finds what it reads.
Taking the biggest coin that fits with coins [1, 3, 4] and an amount of 6 gives 4, 1, 1: three coins. The table finds 3 and 3: two coins. Greedy needs a proof, and a table of the fewest coins for each amount does not.
Explain the three parts in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Repeated work
Q1/2 The recursion for ways(5) makes 15 calls, and only 6 different questions appear in them. What does that mean?
Answer: B
The 15 calls use only the values 0 to 5, which is 6 different questions. The other 9 calls are repeats. The answer is 8, and the repeats are what dynamic programming removes.
Q2/2 A memoised call for ways(3) finds the answer 3 already saved in the memo. What does it do?
Answer: C
A saved answer ends the call. This is how the tree for ways(5) shrinks from 15 calls to 9: three calls read the memo and stop.
Checkpoint · Two ways to remember
Q1/2 Which statement about memoisation and tabulation is true?
Answer: B
Both solve each state once. Memoisation (top down) recurses from the question and saves answers. Tabulation (bottom up) fills a table from the base cases in an order where every cell finds its inputs ready.
Q2/2 For coin change, which sentence is the best state?
Answer: C
A state says in one plain sentence what one cell holds. Here the cell for an amount holds the fewest coins that make exactly that amount, and the rule that fills the table depends on that meaning.
Checkpoint · Base case and order
Q1/2 In the stairs table, how many ways does zero stairs have, and what goes wrong if the table starts with 0?
Answer: B
The base case is the cell you know: staying put is one way. With ways[0] = 0, ways[2] = ways[1] + ways[0] = 1 + 0 = 1, which is wrong, and the error spreads to every later cell.
Q2/2 In a grid table where each cell adds the cell above it and the cell to its left, which order of filling works?
Answer: C
A cell reads the cell above and the cell to its left, so both must be filled first. Row by row from the top, left to right, always has them ready. Any order that reads an empty cell gives the wrong number.
Checkpoint · When greedy fails
Q1/2 Coins are worth 1, 3 and 4. What does the table give for the amount 6, and why does biggest coin first fail?
Answer: C
The table tries every coin for every amount and finds fewest[6] = 2 from fewest[3] + 1. Biggest coin first takes 4, then 1 and 1, which is three coins. The best answer, 3 and 3, has no 4 in it, so the greedy choice is unsafe.
Q2/2 Which question is a good candidate for dynamic programming?
Answer: C
It asks "can it be done", has a choice at each step, and the answer for a prefix is reused by every longer prefix. A largest number or a sort has no repeated smaller question to save, and printing does no search at all.
Checkpoint · Space and cost
Q1/2 Each cell of a table reads only the two cells right before it. How much memory is enough?
Answer: B
Only the last two answers are ever read, so the rest can be forgotten. Keep the whole table only when you need to read the answer back, such as which coins were used.
Q2/2 Fewest coins for an amount of 10,000 with 12 coins. About how many steps does the table take?
Answer: C
The cost is the number of states times the work for each state. There are 10,001 states (the amounts 0 to 10,000), and each tries up to 12 coins. Trying every way to pay is what never finishes.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.