Cache repeated subproblems to turn exponential time into polynomial time.
A cache entry is stored only after its answer is computed, and its key holds every argument that can change the answer.
Use it when the same call, with the same arguments, is made many times. Signal words: count the ways, the best of, the same subproblem again.
Spot: draw the calls, and look for equal arguments in different branches.
Key: name every argument that changes the answer, and nothing else.
Look up: check the cache before any work, and return a stored answer at once.
Store: save the answer under the key before you return.
Cost: the number of different keys times the work for one key, plus the memory for the keys.
The time is the number of different keys times the work for one key. The space is the number of keys. For the ladder, both are about n. The recursion depth is still n, so a very deep ladder needs a table filled in order instead.
def ways_to_climb(n):
return climb(n, {})
def climb(level, cache):
# [1] Base case: levels 0 and 1 each have exactly one way.
if level <= 1:
return 1
# [2] Cache hit: this level was solved before, so return the stored answer.
if level in cache:
return cache[level]
# [3] Solve the level from the two levels below it.
ways = climb(level - 1, cache) + climb(level - 2, cache)
# [4] Store the answer before returning, so the next call finds it.
cache[level] = ways
return wayspublic long waysToClimb(int n) {
return climb(n, new HashMap<>());
}
private long climb(int level, Map<Integer, Long> cache) {
// [1] Base case: levels 0 and 1 each have exactly one way.
if (level <= 1) {
return 1;
}
// [2] Cache hit: this level was solved before, so return the stored answer.
if (cache.containsKey(level)) {
return cache.get(level);
}
// [3] Solve the level from the two levels below it.
long ways = climb(level - 1, cache) + climb(level - 2, cache);
// [4] Store the answer before returning, so the next call finds it.
cache.put(level, ways);
return ways;
}long long climb(int level, unordered_map<int, long long>& cache) {
// [1] Base case: levels 0 and 1 each have exactly one way.
if (level <= 1) {
return 1;
}
// [2] Cache hit: this level was solved before, so return the stored answer.
auto found = cache.find(level);
if (found != cache.end()) {
return found->second;
}
// [3] Solve the level from the two levels below it.
long long ways = climb(level - 1, cache) + climb(level - 2, cache);
// [4] Store the answer before returning, so the next call finds it.
cache[level] = ways;
return ways;
}
long long waysToClimb(int n) {
unordered_map<int, long long> cache;
return climb(n, cache);
}function climb(level, cache) {
// [1] Base case: levels 0 and 1 each have exactly one way.
if (level <= 1) {
return 1;
}
// [2] Cache hit: this level was solved before, so return the stored answer.
if (cache.has(level)) {
return cache.get(level);
}
// [3] Solve the level from the two levels below it.
const ways = climb(level - 1, cache) + climb(level - 2, cache);
// [4] Store the answer before returning, so the next call finds it.
cache.set(level, ways);
return ways;
}
function waysToClimb(n) {
return climb(n, new Map());
}def route_count(down, right):
return routes(down, right, {})
def routes(down, right, cache):
# [1] Base case: on a straight line there is exactly one route.
if down == 0 or right == 0:
return 1
# [2] Cache hit: this pair of distances was solved before, so return the stored answer.
key = (down, right)
if key in cache:
return cache[key]
# [3] Solve the pair from the two neighbours: one step down, or one step right.
total = routes(down - 1, right, cache) + routes(down, right - 1, cache)
# [4] Store the answer under both distances before returning.
cache[key] = total
return totalpublic long routeCount(int down, int right) {
return routes(down, right, new HashMap<>());
}
private long routes(int down, int right, Map<Integer, Long> cache) {
// [1] Base case: on a straight line there is exactly one route.
if (down == 0 || right == 0) {
return 1;
}
// [2] Cache hit: this pair of distances was solved before, so return the stored answer.
int key = down * 100 + right;
if (cache.containsKey(key)) {
return cache.get(key);
}
// [3] Solve the pair from the two neighbours: one step down, or one step right.
long total = routes(down - 1, right, cache) + routes(down, right - 1, cache);
// [4] Store the answer under both distances before returning.
cache.put(key, total);
return total;
}long long routes(int down, int right, unordered_map<int, long long>& cache) {
// [1] Base case: on a straight line there is exactly one route.
if (down == 0 || right == 0) {
return 1;
}
// [2] Cache hit: this pair of distances was solved before, so return the stored answer.
int key = down * 100 + right;
auto found = cache.find(key);
if (found != cache.end()) {
return found->second;
}
// [3] Solve the pair from the two neighbours: one step down, or one step right.
long long total = routes(down - 1, right, cache) + routes(down, right - 1, cache);
// [4] Store the answer under both distances before returning.
cache[key] = total;
return total;
}
long long routeCount(int down, int right) {
unordered_map<int, long long> cache;
return routes(down, right, cache);
}function routes(down, right, cache) {
// [1] Base case: on a straight line there is exactly one route.
if (down === 0 || right === 0) {
return 1;
}
// [2] Cache hit: this pair of distances was solved before, so return the stored answer.
const key = down * 100 + right;
if (cache.has(key)) {
return cache.get(key);
}
// [3] Solve the pair from the two neighbours: one step down, or one step right.
const total = routes(down - 1, right, cache) + routes(down, right - 1, cache);
// [4] Store the answer under both distances before returning.
cache.set(key, total);
return total;
}
function routeCount(down, right) {
return routes(down, right, new Map());
}This version of the routes recursion builds the key from down alone.
This version looks in the cache, but it never stores the answer.
This version creates a new empty cache inside each call.
The skip-or-take recursion for 15 items makes 65,535 calls. Every call has a different list of chosen items, so a cache keyed by the position and the list finds 0 hits and stores 65,535 entries.
systemdesignmastery.dev/dsa/cheatsheets/memoisation-teaser