题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
解法一:循环法
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
a,b = 0,1
for i in range(n):
a,b = b,a+b
return a
解法二:动态规划
class Solution:
def Fibonacci(self, n):
# write code here
if n == 0:
return 0
preInt = 1
postInt = 1
i = 2
while i < n:
preInt = preInt + postInt
postInt = preInt - postInt
i += 1
return preInt
解法三:递归法
def Fibonacci(n):
if n == 0:
return 0
if n == 1 or n == 2:
return 1
return Fibonacci(n-1)+Fibonacci(n-2)