题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
思路
1、老方法递归
直接干了一个普通递归,但是系统判超时
2、 迭代
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
if n is 0 or n is 1:
return n
a = 1
b = 1
while n > 2:
temp = a
a += b
b = temp
n -= 1
return a
3、他山之石
评论区看到一个巧妙的利用python列表增长的方法,简洁优美
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
res=[0,1,1,2]
while len(res)<=n:
res.append(res[-1]+res[-2])
return res[n]