The Fibonacci numbers, commonly denoted F(n)
form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0
and 1
. That is,
F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n > 1.
Given n
, calculate F(n)
.
Example 1:
Input: n = 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 2:
Input: n = 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
Example 3:
Input: n = 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
Constraints:
0 <= n <= 30
## Fibonacci Numbers: Recursive and Iterative Solutions
The Fibonacci numbers are a classic example used in computer science to illustrate recursion and dynamic programming. Given `n`, we want to calculate `F(n)`. Let's explore a couple of approaches.
### 1. Naive Recursive Approach
The most straightforward implementation is a direct translation of the Fibonacci definition.
```python
def fibonacci_recursive(n):
if n <= 1:
return n
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
# Example Usage
n = 10
print(f"F({n}) = {fibonacci_recursive(n)}") # Output: F(10) = 55
The recursive approach is simple but highly inefficient due to redundant calculations. A better solution is to use an iterative approach, building up the Fibonacci numbers from the base cases.
def fibonacci_iterative(n):
if n <= 1:
return n
a, b = 0, 1
for _ in range(2, n + 1):
a, b = b, a + b
return b
# Example Usage
n = 10
print(f"F({n}) = {fibonacci_iterative(n)}") # Output: F(10) = 55
Memoization is a top-down dynamic programming technique where we store the results of expensive function calls and reuse them when the same inputs occur again. This avoids redundant calculations.
def fibonacci_memoization(n, memo={}):
if n in memo:
return memo[n]
if n <= 1:
return n
memo[n] = fibonacci_memoization(n-1, memo) + fibonacci_memoization(n-2, memo)
return memo[n]
# Example Usage
n = 10
print(f"F({n}) = {fibonacci_memoization(n)}") # Output: F(10) = 55
fibonacci_recursive(n)
results in two more calls, forming a binary tree structure. Many of these calls are redundant, recalculating the same Fibonacci numbers multiple times.n
once to compute the Fibonacci number.memo
dictionary. Subsequent calls for the same n
take O(1) time.n
.a
, b
).memo
dictionary storing computed Fibonacci numbers and also O(n) for the call stack.n
. If negative values were required, the definition would need to be extended (e.g., using F(-n) = (-1)^(n+1) * F(n)
).n
, the recursive approach will cause a stack overflow due to the excessive number of function calls. The iterative approach is much more robust for large n
values and memoization can further optimize it.