剑指offer第7题 牛客网在线编程链接 https://www.nowcoder.com/activity/oj
斐波那契数列
题目描述
要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。n<=39
思路1:递归
当n = 0时,Fibonacci = 0;当n = 1时,Fibonacci = 1;当n >= 2时,Fibonacci(n) = Fibonacci(n - 1) + Fibonacci(n - 2)
Python2.7编写
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return self.Fibonacci(n - 1) + self.Fibonacci(n - 2)
思路2:递归的解法效率太低,用迭代的方法解决
Python2.7编写
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
f = 0
g = 1
if n == 0:
return 0
elif n == 1:
return 1
else:
for i in range(2,n+1):
f,g = g,f + g
return g