題目描述:
大家都知道斐波那契數(shù)列偿曙,現(xiàn)在要求輸入一個(gè)整數(shù)n惩猫,請(qǐng)你輸出斐波那契數(shù)列的第n項(xiàng)嘁灯。
解題思路:
- 斐波那契數(shù)列定義如下:F(1)=1辞友,F(xiàn)(2)=1, F(n)=F(n-1)+F(n-2)(n>=2,n∈N*)
1.根據(jù)定義溃睹,最先想到的是遞歸的解法而账,但是當(dāng)n較大時(shí),遞歸的效率會(huì)很低因篇;是隨著n呈指數(shù)增長(zhǎng)的泞辐。 - 可以將已得到的中間項(xiàng)保留,所以最直觀的方法就是從下往上計(jì)算竞滓。時(shí)間復(fù)雜度O(n)咐吼。b表示后面的一個(gè)數(shù)字,a表示前面的數(shù)字即可商佑。每次進(jìn)行的變換是:temp = a锯茄,a=b,b=temp + b
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
# 斐波那契數(shù)列定義F(1)=1茶没,F(xiàn)(2)=1, F(n)=F(n-1)+F(n-2)(n>=2肌幽,n∈N*)
if n<=0:
return 0
else:
a = 1
b = 1
while n > 2:
temp = a
a = b
b = temp + b
n = n - 1
return b