To implement the Fibonacci sequence using dynamic programming with a top-down approach, we can use memoization technique. Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again.
Using memoization, we can avoid repetitive calculations and reduce the time complexity of the algorithm. In the case of the Fibonacci sequence, we can recursively calculate the Fibonacci numbers and store their results in an array or a HashMap. This way, we can avoid calculating the same Fibonacci numbers multiple times.
Here is the Java code for implementing the Fibonacci sequence using dynamic programming with a top-down approach:
public class FibonacciDP {
private static Map<Integer, Integer> memo = new HashMap<>();
public static int fib(int n) {
if (n <= 1) {
return n;
}
if (memo.containsKey(n)) {
return memo.get(n);
}
int result = fib(n-1) + fib(n-2);
memo.put(n, result);
return result;
}
public static void main(String[] args) {
int n = 10;
for (int i = 0; i <= n; i++) {
System.out.print(fib(i) + " ");
}
}
}
In this code, we have defined a private static HashMap called memo that will store the Fibonacci numbers that we have already computed. The fib() method takes an integer argument n and returns the nth Fibonacci number. If n is less than or equal to 1, the method returns n. Otherwise, it checks if memo already contains the value of n. If so, it returns that value. Otherwise, it recursively calculates the nth Fibonacci number using the formula fib(n-1) + fib(n-2), stores the result in memo, and returns the result.
In the main method, we have defined n as 10, and we are calling the fib() method for each value of i from 0 to 10. The output of this code will be:
0 1 1 2 3 5 8 13 21 34 55
As we can see, the Fibonacci numbers have been calculated using dynamic programming with a top-down approach, and the results have been cached in memo to avoid repetitive calculations. This approach has a time complexity of O(n), where n is the index of the Fibonacci number we want to calculate.