10. 斐波那契数列
斐波那契数列
http://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3
- 递归,为了提高效率,我们需要利用一个辅助的结果列表result,计算过的n和Fibonacci(n)对储存在里面,避免重复计算
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
result = {0:0, 1:1}
def helper(n):
if n in result:
return result[n]
res = helper(n-1) + helper(n-2)
result[n] = res
return res
return helper(n)
- 利用矩阵
https://blog.csdn.net/lamusique/article/details/89161831 - 更简单实用的是用循环来做
class Solution:
def Fibonacci(self, n):
# write code here
res = [0,1,1,2]
while len(res)-1 < n:
res.append(res[-1]+res[-2])
return res[n]