




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 <iostream>
2using namespace std;
3
4int fibonacci(int n) {
5    if (n <= 1)
6        return n;
7    return fibonacci(n - 1) + fibonacci(n - 2);
8}
9
10int main() {
11    int n = 4;
12    cout << fibonacci(n);
13    return 0;
14}This C++ program uses a recursive function 'fibonacci' similarly to the C solution to compute the nth Fibonacci number using recursion.
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 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.