原题
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
Reference Answer
解题思路:
直接用回溯法了,用递归效率低。
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
res = []
res.append(0)
res.append(1)
# res[0], res[1] = 0, 1
if n > 1:
for i in range(2, n+1):
res.append(res[i-1] + res[i-2])
return res[n]