题目描述:
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。n<=39
答案:
不通过解法:
使用递归思想处理,超过时间限制
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
if n == 0:
return 0
elif n == 1:
return 1
else:
value = self.Fibonacci(n-1)+self.Fibonacci(n-2)
return value
正确解法:
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
if n == 0:
return 0
elif n == 1:
return 1
else:
f0 = 0
f1 = 1
value = 0
for i in range(2,n+1):
value = f0 + f1
f0 = f1
f1 = value
return value