題目描述
大家都知道斐波那契數(shù)列,現(xiàn)在要求輸入一個(gè)整數(shù)n秧耗,請(qǐng)你輸出斐波那契數(shù)列的第n項(xiàng)(從0開始,第0項(xiàng)為0)车猬。
n<=39
思路:
斐波那契數(shù)列: 0 1 1 2 3 5 ...
滿足 f(n) = f(n-1)+f(n-2)
遞歸很好寫尺锚,但是吧不給過(guò),只能寫個(gè)非遞歸吧瘫辩。代碼很簡(jiǎn)單:
class Solution:
def Fibonacci(self, n):
# write code here
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
pre_2 = 1
pre_1 = 1
result = 0
for i in range(3,n+1):
result = pre_2 + pre_1
pre_2 = pre_1
pre_1 = result
return result