Memoization ensures that a function doesn't run for the same inputs more than once by keeping a record of the results for the given inputs (usually in a dictionary).
For example, a simple recursive function for computing the nth Fibonacci number:
Will run on the same inputs multiple times:
We can imagine the recursive calls of this function as a tree, where the two children of a node are the two recursive calls it makes. We can see that the tree quickly branches out of control:
To avoid the duplicate work caused by the branching, we can wrap the function in a class with an attribute, memo, that maps inputs to outputs. Then we simply
- check memo to see if we can avoid computing the answer for any given input, and
- save the results of any calculations to memo.
We save a bunch of calls by checking the memo:
Now in our recurrence tree, no node appears more than twice:
Memoization is a common strategy for dynamic programming problems, which are problems where the solution is composed of solutions to the same problem with smaller inputs (as with the Fibonacci problem, above). The other common strategy for dynamic programming problems is going bottom-up, which is usually cleaner and often more efficient.