劍指offer-斐波那契數列

你們都知道斐波那契數列,如今要求輸入一個整數n,請你輸出斐波那契數列的第n項。post

n<=39spa

 

一隻青蛙一次能夠跳上1級臺階,也能夠跳上2級。求該青蛙跳上一個n級的臺階總共有多少種跳法。code

對於第n個臺階來講,只能從n-1或者n-2的臺階跳上來,因此
F(n) = F(n-1) + F(n-2)
斐波拉契數序列,初始條件
n=1:只能一種方法
n=2:兩種
#動態規劃版
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)
相關文章
相關標籤/搜索