Builds onRecursion and the call stack
01The idea
Some recursive solutions solve the same smaller problem again and again. Dynamic programming, or DP, solves each smaller problem once, stores the answer, and reads it back when it is needed again. A solution that took exponential time can drop to linear time.
To use DP, you need four things:
- The state. What does one stored answer mean? Write it as a sentence, such as "ways[i] is the number of ways to tile a strip of length i".
- The recurrence. How does one answer follow from smaller ones? Look at the last decision. Each possible last decision leaves a smaller problem you have already solved.
- The base case. The smallest state, whose answer you know without the recurrence.
- The order. Fill the states so that each one only reads states that are already filled.
There are two ways to write it. Top-down keeps the recursive function and adds a dictionary, called a memo, that stores each result. Bottom-up fills an array in a loop, from the base case upward. Both do the same work. Bottom-up avoids deep recursion, and it is easier to cut down to less memory.
In one-dimensional DP the state is a single number, a position or a size. The array has one entry per value of it.
02How to spot it
DP fits when:
- the question asks for the number of ways, the minimum, the maximum, or whether something is possible
- the answer for a size or position is built from the answers for smaller ones
- a plain recursion would call itself on the same arguments many times
Look at the last step of any solution. If every solution ends with one of a few choices, and each choice leaves a smaller copy of the problem, you have a recurrence.
Greedy problems look similar but make one choice without looking back. When a greedy choice can be wrong, DP tries every last choice and keeps the best.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue