牛客網《劍指offer》之Python2.7實現:斐波那契數列
阿新 • • 發佈:2018-12-10
題目描述
大家都知道斐波那契數列,現在要求輸入一個整數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]