Part 2 of 7 · Spot the dynamic programLearn and do
Plain recursion asks the same question millions of times
The formula is correct. The question is what it costs.
Predict
Plain recursion makes 50 cents from coins of 1, 5, 10 and 25. About how many calls?
Write that formula as a plain recursive function, and it asks for the same amounts over and over:
Calls, plain recursion against once per amount
50¢, recursion
7.3 million
$1, recursion
32.5 trillion
$1, once each
101
Those counts use coins of 1, 5, 10 and 25 cents. Yet a dollar has only 101 different questions to ask, the amounts 0 through 100. This is called overlapping subproblems: the same smaller questions come up again and again.
Answer each amount once and store it. Then a dollar costs 101 amounts times 4 coins. That's a dynamic program, a DP for short: solve each smaller amount once, keep the answer, and build bigger answers from the kept ones.
That's the shape to recognize: an exact target, choices that each shrink it, and a best answer or a count over all the ways. Knapsack problems, where you fill a bag up to a weight limit, look the same.
In the editor, naive is the formula as plain recursion, making 20 cents from coins of 1, 2 and 5. Make it add 1 to calls[0] each time it runs, then set distinct to how many different amounts it can ever ask about on the way down from 20.
Pick an answer above to see the rest
Instructions
1
Add 1 to calls[0] every time naive runs.
2
Set distinct: how many different amounts the recursion can ask about, from 0 to 20.