Sponsored
Sponsored
The dynamic programming approach breaks the problem into smaller, more manageable sub-problems. We then solve each sub-problem once, store its result, and use these results to construct the solution to the original problem in an efficient manner, avoiding repeated calculations.
Time Complexity: O(n)
Space Complexity: O(n)
1import java.util.*;
2
3public class Fibonacci {
4 public static int fibonacci(int n) {
5 int[] dp = new int[n + 1];
6 dp[1] = dp[2] = 1;
7 for (int i = 3; i <= n; i++) {
8 dp[i] = dp[i - 1] + dp[i - 2];
9 }
10 return dp[n];
11 }
12
13 public static void main(String[] args) {
14 int n = 10;
15 System.out.println("Fibonacci number is " + fibonacci(n));
16 }
17}
The Java solution leverages an integer array to store Fibonacci values in a dynamic programming approach to compute the nth Fibonacci number efficiently by avoiding repeated calculations.
The recursive approach with memoization involves using a recursive function to calculate Fibonacci numbers and memorizing results of previously computed terms. It reduces the overhead of repeated computations by storing results in a data structure (e.g., dictionary).
Time Complexity: O(n)
Space Complexity: O(n) due to memoization array.
1
In Python, a dictionary is used for memoization. This stores results of previously computed Fibonacci numbers, enhancing efficiency by preventing redundant calculations.