题目描述
输入一个整数 nn ,求斐波那契数列的第 nn 项。
假定从0开始,第0项为0。(nn<=39)
样例
输入整数 n=5
返回 5
Python3 代码1(递归-Time Limit Exceeded)
### Python3 代码1
class Solution(object):
def Fibonacci(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
if n == 1:
return 1
return self.Fibonacci(n-1) + self.Fibonacci(n-2)
Python3 代码2(迭代)
### Python3 代码2
class Solution(object):
def Fibonacci(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
a, b = 0, 1
# 单下划线用作临时变量
for _ in range(n-1):
a, b = b, a+b
return b