请用三种方式写出求斐波那契数列第 n 项,包括普通递归,带缓存数 组的递归以及递推法。斐波那契数列的公式如下: f(n) = 1 if n = 1, 2 f(n − 1) + f(n − 2) if n > 2
时间: 2024-10-22 11:13:21 浏览: 35
解题步骤-递归与递推深入
当然可以,下面是三种求解斐波那契数列第n项的不同方法:
1. **普通递归** (效率较低)
```python
def fibonacci_recursive(n):
if n <= 0:
return "错误,n必须大于0"
elif n == 1 or n == 2:
return n
else:
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
# 示例
print(fibonacci_recursive(10))
```
2. **带缓存数组的递归** (也称动态规划)
```python
def fibonacci_with_cache(n, cache={}):
if n <= 0:
return "错误,n必须大于0"
if n in cache:
return cache[n]
elif n == 1 or n == 2:
result = n
else:
result = fibonacci_with_cache(n - 1, cache) + fibonacci_with_cache(n - 2, cache)
cache[n] = result
return result
# 示例
print(fibonacci_with_cache(10))
```
3. **迭代(递推法)**
```python
def fibonacci_iterative(n):
if n <= 0:
return "错误,n必须大于0"
a, b = 0, 1
for _ in range(n - 1):
a, b = b, a + b
return b
# 示例
print(fibonacci_iterative(10))
```
阅读全文