




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.
1#include <stdio.h>
2
3int fibonacci(int n) {
4    if (n <= 1) 
5        return n;
6    return fibonacci(n - 1) + fibonacci(n - 2);
7}
8
9int main() {
10    int n = 4;
11    printf("%d", fibonacci(n));
12    return 0;
13}This C program defines a recursive function 'fibonacci' which returns the nth Fibonacci number by recursively calling itself with (n-1) and (n-2) until reaching the base cases of 0 or 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.
1def
In Python, the dynamic programming solution uses a list 'fib' to store results up to 'n', computed iteratively. This eliminates redundant calculations like those in recursive solutions.