All episodes · From a List to Your Map App · Episode 22

Never Solve the Same Thing Twice: Dynamic Programming

Pressing play loads the video from YouTube.

How many ways can you climb six stairs, one or two at a time? Thirteen. But the obvious program gets painfully slow as the stairs grow.
We see why the ways to each step are the two below it added together, watch the plain recursion repeat itself (fifteen calls for six stairs, over two hundred million for forty), then fix it by writing each answer down: memoization, or a row of cells filled from the bottom up. Finally we go back to episode 15's coins (one, three and four, making six) and let a table find the answer greedy missed: three plus three.

Every animation in this video is drawn by code, and the narration is an AI voice.

Transcript

How many ways can you climb six stairs, one or two at a time? Thirteen. But the obvious program for this gets painfully slow as the stairs grow. The fix is one simple habit: never solve the same small problem twice. Today: dynamic programming.

To reach step six, your last move came from step five or from step four. So the ways to six are the ways to five plus the ways to four. Step one has one way, step two has two. Every other step is just the two below it added together.

Written as recursion, from episode four, ways of six calls five and four; five calls four and three; and it keeps branching. Look at the repeats: four is worked out twice, three three times, and the whole tree makes fifteen calls for one answer. For forty stairs, that's over two hundred million calls, for a question with forty steps.

Instead, write each answer down the first time, and just look it up after that. That's called memoization. Or fill a row of cells from the bottom up: one, two, three, five, eight, thirteen. Forty stairs, forty cells.

Now back to the coins from episode fifteen: one, three and four, making six. Fill a table with the fewest coins for every amount, from zero up. For each amount, try every coin: the fewest for whatever is left, plus one. At six, using a three leaves three, which takes one coin. Two coins in total: three plus three, the answer greedy missed.

Spot the small problems that repeat, solve each one once, and keep the answers. That's dynamic programming. Next time: how a spell checker guesses the word you meant to type. See you there.

Next episode: how a spell checker guesses the word you meant to type.

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal