




Sponsored
Sponsored
The recursive approach involves directly applying the Fibonacci formula: F(n) = F(n-1) + F(n-2). This approach naturally follows the definition of the Fibonacci sequence, solving subproblems by calling itself. However, this naive implementation leads to overlapping subproblems and higher time complexity.
This recursive solution is easy to implement but inefficient for larger n due to exponential time complexity.
Time Complexity: O(2^n) because it grows exponentially, with overlapping subproblems.
Space Complexity: O(n) due to the recursion stack required by function calls.
1public class Fibonacci {
2    public static int fibonacci(int n) {
3        if (n <= 1) return n;
4        return fibonacci(n - 1) + fibonacci(n - 2);
5    }
6
7    public static void main(String[] args) {
8        int n = 4;
9        System.out.println(fibonacci(n));
10    }
11}This Java program implements a recursive function 'fibonacci' that calculates the nth Fibonacci number. The method uses recursion, calling itself with (n-1) and (n-2) until the base case of n <= 1.
The dynamic programming approach involves using an array to store previously computed Fibonacci numbers, which prevents redundant calculations found in the recursive approach. This method significantly improves efficiency by transforming the exponential recursive solution into a linear solution, using merely linear space.
Time Complexity: O(n) due to linear iteration.
Space Complexity: O(n) for the array storing Fibonacci numbers.
1
In this C solution, an array 'fib' is used to store Fibonacci numbers up to n. The base cases are initialized, and the array is filled iteratively, computing each Fibonacci number from the two preceding numbers, achieving a linear time complexity.