Loading...
Master memoization, tabulation, and advanced DP patterns
Section 0 of 0
Master memoization, tabulation, and advanced DP patterns
Building a DP solution requires choosing between two fundamental implementation routes. Master the trade-offs between Top-Down caching and Bottom-Up table filling.
This approach starts with the original large problem and recursively breaks it down. Before solving a sub-problem, we check if it is already in our cache (the "memo table").
1function minCoins(amount, coins, memo):2 if amount == 0: return 03 if amount < 0: return +INF4 5 if memo[amount] exists: 6 return memo[amount] // CACHE HIT7 8 best = +INF9 for c in coins:10 best = min(best, 1 + minCoins(amount - c, coins, memo))11 12 memo[amount] = best // CACHE SAVE13 return bestOften in Tabulation, you only need the previous row or even just the previous few values to calculate the current state. By using only O(1) or O(min(m, n)) space, you can save significant memory while maintaining O(n^2) speed.