From recursion to memo to table

Video lessonComing soon

1 A robber on a street

Five houses stand in a row, with 3, 8, 4, 2 and 6 thousand rupees in them. A robber wants to take as much as he can in one night. Two houses next to each other share an alarm, so he never robs two neighbours. This is House Robber.

3081422364
nums. The best plan robs houses 1 and 4 for 14

Robbing every other house gives 3 + 4 + 6 = 13. The best plan is 8 + 6 = 14, and it skips two houses in a row. No fixed pattern works, so we have to try the choices.

The pick-or-skip lesson tried every choice with a tree, and it made about 2ⁿ calls. Here n can be 10⁵. This lesson takes that kind of recursion and makes it fast in two moves. First it saves each answer the first time it is calculated. Then it fills a table without any recursion. This route, from recursion to memo to table, is dynamic programming, or DP for short.

2 The recursion: state, choice, base cases

We ask one question, best(i): the most money from the first i houses, houses 0 to i − 1. The answer for our street is best(5).

To answer it, we look only at the last of those houses, house i − 1. It gives the take-or-skip choice:

  • Skip it. The first i − 1 houses are all still open, so we get best(i − 1).
  • Take it. We get nums[i - 1], but its neighbour, house i − 2, is now off limits. The rest comes from the first i − 2 houses, so we get nums[i - 1] + best(i − 2).

Every plan does one of the two. The best plan that skips is worth best(i − 1), and the best plan that takes is worth nums[i - 1] + best(i − 2). So the larger of them is the best of all.

Every DP needs the same three things. Here they are for House Robber:

PartQuestionHouse Robber
StateWhat changes from call to call?i, how many houses are open
TransitionHow does a state come from smaller ones?the larger of skip and take
Base casesWhich states are answered directly?best(0) = 0, best(1) = nums[0]
best(i) = max(best(i − 1), nums[i − 1] + best(i − 2))

The base cases are the states the formula cannot reach below. With one house, best(1) would ask for best(−1), so we answer it directly: the robber takes the one house.

best(i)
    if i == 0
        return 0
    if i == 1
        return nums[0]
    skip = best(i - 1)
    take = nums[i - 1] + best(i - 2)
    return max(skip, take)

3 The same questions, again and again

Each call makes two calls, on i − 1 and i − 2. That is the shape of the fib tree from the recursion tree lesson. Here are the calls of best(5), with each node showing its i:

Repeated calls in best(5)
120314120512031
best(3) and all its calls run twice
CallTimes made
best(5)1
best(4)1
best(3)2
best(2)3
best(1)5
best(0)3

There are only 6 different questions, best(0) to best(5), but the tree makes 15 calls. It grows like the fib tree: about 22,000 calls at n = 20, and about 4 × 10¹⁰ at n = 50. At n = 10⁵ it is far past the time limit, so it gets TLE.

The answer to best(3) depends on i alone. It is 8 every time anyone asks. So the second time, we could hand back the first answer instead of calculating it again.

4 Memoisation: save each answer

Memoisation keeps the recursion and adds a cache, memo, with one slot per state. Every slot starts at −1, which means "not calculated yet". Money is never negative, so −1 cannot be a real answer. A call first checks its slot. If the slot is filled, the call returns it at once. This is a cache hit. Otherwise, the call works out the answer, saves it in the slot, and returns it.

Here is best(5) with the memo. A ✓ marks a call that was a cache hit:

best(5) with a memo
1203142✓53✓
Calls go down the left side to best(2)
-10-11-12-13-14-15
memo

In step 4, best(4) takes 2 + 8 = 10, where the 8 comes straight from the memo. The tree shrinks from 15 calls to 9. Each state is calculated once, and the two hits have no calls below them. Slots 0 and 1 stay at −1, because the base cases return before the memo is checked.

Every tab returns 14 on [3, 8, 4, 2, 6] and 7 on [7]. The code is the recursion from section 2 with three lines added: make the memo, check the slot, save the answer.

C++

Pass memo by reference. Without the &, every call gets its own copy of the vector. The saved answers never reach the other calls, and the code is as slow as the plain recursion.

Arrays.fill sets the −1. A new long[] starts full of 0s. The array is shared by every call, because Java passes a reference to it.

A nested function. best lives inside rob, so it can read nums and memo without passing them. It only changes the list's slots, so it needs no nonlocal.

A closure. best lives inside rob, so it can read nums and memo without passing them. Each call to rob gets a fresh memo.

The slice shares memory. Passing memo copies only a small header, and every call writes into the same slots.

&mut Vec<i64>. Every call borrows the one memo, can write into it, and lends it on to the calls it makes.

Array.Fill sets the −1. A new long[] starts full of 0s. The array is shared by every call, because C# passes a reference to it.

5 Tabulation: fill a table from the bottom up

Look at the order in which the memo filled its slots: 2, 3, 4, then 5. Each slot needed only the two slots before it. So we can fill the same slots in a plain loop, with no calls at all. This is tabulation.

The table best has n + 1 slots, one per state. We write the base cases into slots 0 and 1 first: 0 and 3. Then the loop fills slots 2 to 5, left to right. Each arrow shows a slot the new value reads:

Filling the table
3081422364
nums: house 1
003182345
best[2] = max(3, 0 + 8) = 8
iHouse i − 1skip = best[i − 1]take = best[i − 2] + nums[i − 1]best[i]
2830 + 8 = 88
3483 + 4 = 78
4288 + 2 = 1010
56108 + 6 = 1414

The last slot holds 14, the same answer as the memo, from the same four steps in the same order. At i = 3, skip wins, and best[3] copies best[2]. That is where the plan leaves two houses in a row.

Every tab returns 14 on [3, 8, 4, 2, 6], 7 on [7], and 50000000000000 on 10⁵ houses of 10⁹ each. With one house the loop never runs, and best[1] is the answer.

6 Memo or table, and the cost

The memo works top-down: it starts at best(n) and lets the recursion ask for what it needs. The table works bottom-up: it starts at the base cases and climbs.

Memo, top-downTable, bottom-up
Order of workWhatever the recursion asksWe choose it in the loop
Writing itAdd a cache to the recursionWork out the fill order first
States calculatedOnly the ones the calls reachAll of them
Call stackUp to n calls deepNone
At n = 10⁵Can overflow the stack: Runtime ErrorFine

The cost of any DP is the number of states times the work for one state. Here there are n + 1 states, and each one takes the larger of two values, which is O(1). So both versions take O(n) time, about 10⁵ steps at n = 10⁵, against about 2ⁿ for the plain recursion. Both keep n + 1 slots, so the space is O(n).

7 Mistakes and edge cases

  • A memo key missing a parameter. The key must hold everything the answer depends on. If the robber may rob at most k houses, the state is (i, k). A memo keyed by i alone hands back an answer worked out for a different k. On [8, 3, 9, 6, 8] with k = 2, the answer is 17, but that memo returns 25, which robs three houses.
  • 0 as "not calculated". When 0 can be a real answer, a slot holding 0 looks empty forever. On a street of 50 empty houses, every slot stays 0, the memo never hits, and the code makes about 4 × 10¹⁰ calls: TLE. Start the slots at −1, or at an empty value such as null. No answer can take either value.
  • A missing base case. With only best(0) = 0, best(1) asks for best(−1). That reads outside the array: Runtime Error.
  • Filling in the wrong order. A loop from i = n down to 2 reads slots that are still 0. On our street, best[5] becomes max(0, 0 + 6) = 6, and the code returns 6 instead of 14.
  • Overflow. With 10⁵ houses of 10⁹ each, the robber takes 5 × 10¹³, far past the 32-bit limit of about 2 × 10⁹. Keep the totals in long long.

8 When a problem needs DP

A problem needs DP when it shows two signs:

  • The same question comes up again. The recursion tree has repeated calls, like best(3) above. These are overlapping subproblems.
  • The best answer is built from the best answers to smaller questions. best(i) uses best(i − 1) and best(i − 2), and it does not care which houses they robbed. This is optimal substructure.

In this section, the sign is a choice at each position: take it or skip it, and the answer builds on the ones before. Climbing Stairs counts ways instead of money, so it adds the two smaller answers instead of taking the larger. In Decode Ways, the choice is to read one digit or two. Each time, the three parts from section 2 come first: the state, the transition and the base cases.

The table reads only the two slots before each new one. The next lesson keeps just those two values and drops the rest of the table.

The habit to keep: write the recursion and name its state first. If the tree repeats a call, add a memo keyed by the whole state. Then fill a table in the order the formula reads it.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.