1. 程式人生 > >7.斐波那契數列-劍指offer-Python2.7

7.斐波那契數列-劍指offer-Python2.7

劍指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