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

劍指offer 8. 斐波那契數列

原題

大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項(從0開始,第0項為0)。 n<=39

Reference Answer

解題思路:

直接用回溯法了,用遞迴效率低。

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        res = []
        res.append(0)
        res.append(1)
        # res[0], res[1] = 0, 1
        if n >
1: for i in range(2, n+1): res.append(res[i-1] + res[i-2]) return res[n]