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.