剑指offer 斐波那契数列 @python
题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。
n<=39
Solution
求斐波那契数列有3中方法:
- 递归
- 循环
使用递归方法,由于有较多重复计算,时间复杂度过高,可以使用循环自下而上的求解。
递归
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 21 20:13:53 2018
@author: Saul
"""
-*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
if n == 0:
return 0
if n == 1:
return 1
res = self.Fibonacci(n-1) + self.Fibonacci(n-2)
return res
循环
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 21 20:13:53 2018
@author: Saul
"""
# -*- coding:utf-8 -*-
class Solution:
def Fibonacci(self, n):
# write code here
if n == 0:
return 0
if n == 1:
return 1
F1 = 0
F2 = 1
for i in range(2,n+1):
Fn = F1 + F2
F1 = F2
F2 = Fn
return Fn