题目
题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
解题思路
- 判断n是否为0,1,2,对应特殊值;
- 否则返回第n项的结果。
注:循环可通过,但递归不行。
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
if n==0:
return 0
if n==1 or n==2:
return 1
#return self.Fibonacci(n-1)+ self.Fibonacci(n-2)
first=1
second=1
while n>2:
first, second = second, second+first
n-=1
return second