Dynamic programming tutorial

Memoization and tablesWorld 5 tutorial
0:00 / 0:00

Never solve the same problem twice. Save each answer as you recurse, or fill a table from the smallest case up.

▼

Transcript

Welcome to the Dynamic Programming world. The whole move fits in one line: never solve the same problem twice.

Take a row where each number is the sum of the two before it. To find F of five, plain recursion asks for F of four and F of three, and so on, all the way down. But F of three gets solved twice, and F of two three times. That's fifteen calls, and the count grows exponentially.

So save each answer the first time you solve it. Every repeat becomes a lookup, and the branches under it vanish: nine calls instead of fifteen.

Or turn it around and build up from the smallest case. Fill a row of answers: zero and one, then each cell from the two before it: one, two, three, five.

The clue: the problem asks for a count, a best, or a yes or no, and the answer for one size depends on smaller sizes.

The cost: states times the work per state. Here, n states with one addition each: linear time.

Now let's use it on Climbing Stairs.