Look first. Store last.
transcript
Add a cache to a recursion. Only two lines change. One looks. One stores. The rest stays the same.
At the top, check the cache. If the key is there, return. No recursive call is made. The lookup costs almost nothing.
Solve the problem as before. Save the answer under the key. Then return it to the caller. Now the next call finds it.
Without the cache: 2,692,537 calls. With the cache: 59 calls. Both return 1,346,269.
Make the cache outside the recursion. Pass it down each call. A new cache per call never hits.
Six levels make eleven calls. Three of them are hits. Thirty levels make 59 calls. Twenty-seven of them are hits.
Store before every real return. Otherwise nothing is ever found. The answer stays right, but slow. Check the cache with a counter of hits.
Two lines, a huge saving. The answer does not change. Only the work shrinks. Full breakdown in the lecture.