Memoization is a technique in dynamic programming where the results of expensive function calls are cached or stored to avoid redundant calculations. It is a top-down approach of dynamic programming.
In more technical terms, memoization is an optimization technique where the result of a function call is stored in memory so that subsequent calls with the same inputs can be returned from the cache instead of recalculating the results.
Dynamic programming, on the other hand, is a bottom-up approach that breaks down a problem into smaller subproblems to solve them recursively. The solutions to the subproblems are then combined to solve the larger problem.
Memoization can be used in dynamic programming to optimize the time complexity of a recursive solution. When solving a problem recursively, there is a possibility that the same subproblem will be solved multiple times. By memoizing the results of these subproblems, we can avoid solving them repeatedly and thereby reduce the time complexity of the code.
Heres an example Java code that implements memoization in a dynamic programming solution to compute the nth Fibonacci number:
import java.util.*;
public class Fibonacci {
static Map<Integer, Integer> memo = new HashMap<>();
public static int fibonacci(int n) {
if (n <= 1) {
return n;
} else if (memo.containsKey(n)) {
return memo.get(n);
} else {
int result = fibonacci(n - 1) + fibonacci(n - 2);
memo.put(n, result);
return result;
}
}
public static void main(String[] args) {
System.out.println(fibonacci(6)); // Output: 8
}
}
In this code, we use a ‘Map‘ to store the results of previous function calls using memoization. Each time the ‘fibonacci‘ function is called with a value of ‘n‘, we first check if the result has already been memoized using ‘memo.containsKey(n)‘. If so, we simply return the memoized result using ‘memo.get(n)‘. Otherwise, we compute the result recursively and store it in the ‘Map‘ using ‘memo.put(n, result)‘.
By using memoization, we avoid calculating the same Fibonacci numbers multiple times and greatly improve the performance of our code, especially for large values of ‘n‘.