斐波那契数列
定义:F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=3,n∈N*)
基础实现,速度很慢
def f(n): if n < 2: return 1 return f(n-1) + f(n-2) print(f(300)) # 第三百个数字
类似尾调用,速度快
def f(n, a=0, b=1): if n < 2: return 1 return b+f(n-1, b, a + b) print(f(900)) # 第九百个数字
返回数列
def f(n, a=0, b=1, l=[1]): if n < 2: return 1 else: l.append(a+b) f(n-1, b, a + b) return l print(f(900)) # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, ...]
注意:使用递归调用时,Python默认最大递归次数1000次,超过会报栈溢出。
迭代器实现,快、耗资源少
def f(n): a, b = 1, 1 while n: yield a a, b = b, a+b n -= 1 for x in f(5000): print(x, end=' ') # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...]
class Solution: def fib(self, N: int) -> int: if N == 0: return 0 a, b, c= 0, 1, 0 for x in range(N-1): c = a a = b b = c + b return b