Memoization and dynamic programming are techniques used to optimize algorithms by avoiding redundant calculations and storing intermediate results for future use
Memoization involves caching the results of function calls to avoid calculations. It is often used in combination with recursion
Dynamic programming is a technique for solving problems by breaking them down into overlapping sub-problems and storing the solutions to sub-problems in a table to avoid redundant calculations
This is an example of memoization and dynamic programming
def fib(n, memo = {})
if (n === 0 || n === 1) return n
if (!memo[n])
return (memo[n] = fibonacci(n - 2, memo) + fibonacci(n - 1, memo))
return memo[n]
end
- When you need to optimize a recursive algorithm
- When solving problems that can be broken down into smaller sub-problems and have an optimal substructure