说明:
斐波那契数列问题有两种解法,一种是递归,一种是非递归,递归方法会引入大量重复计算,及其耗时间,不推荐。非递归之所以快是因为存储了临时结果以便下一次计算使用。
代码:
# 斐波那契数列问题
# 递归
def func(n):
if n == 1 or n == 2:
return 1
return func(n-1) + func(n-2)
# 非递归
tmpret = [1,1]
def funcA(n):
record = n
while n>2:
tmpret.append(tmpret[record-n] + tmpret[record-n+1])
n=n-1
return tmpret[record-1]
print(funcA(30))