Java program for Fibonacci Series
class FibonacciSeries {
int[] dp;
// Time Complexity O(2^n) and Space Complexity O(n)
int fibonacci_recursive(int n) {
if(n <= 1) { //To return 1st and 2nd term
return n;
}
return fibonacci_recursive(n-2) + fibonacci_recursive(n-1);
}
// Time Complexity O(n) and Space Complexity O(n)
int fibonacci_recursive_memoization(int n) {
if(n <= 1) { //To return 1st and 2nd term
return n;
}
if(dp[n-2] == -1) {
dp[n-2] = fibonacci_recursive(n-2);
}
if(dp[n-1] == -1) {
dp[n-1] = fibonacci_recursive(n-1);
}
dp[n] = dp[n-2] + dp[n-1];
return dp[n];
}
// Time Complexity O(n) and Space Complexity O(1)
int fibonacci_iterative(int n) {
if(n <= 1) { //To return 1st and 2nd term
return n;
}
int term1 = 0, term2 = 1, sum = n;
for(int i = 2; i <=n; i++) {
sum = term1 + term2;
term1 = term2;
term2 = sum;
}
return sum;
}
public static void main (String[] args) {
FibonacciSeries obj = new FibonacciSeries();
int n = 8;
System.out.println(obj.fibonacci_recursive(n));
obj.dp = new int[] {-1,-1,-1,-1,-1,-1,-1,-1,-1};
System.out.println(obj.fibonacci_recursive_memoization(n));
System.out.println(obj.fibonacci_iterative(n));
}
}
Comments
Post a Comment