1. 程式人生 > 實用技巧 >斐波那契數列及簡單dp應用

斐波那契數列及簡單dp應用

斐波那契數

  • 問題:現在要求輸入一個整數n,請你輸出斐波那契數列的第n項(從0開始,第0項為0,第1項 是1)。 n<=39

  • 解決:

    #方法一:迭代
    class Solution:
        def fib(self, N: int) -> int:
            if N < 2:
                return N
            first = 0
            second = 1
            third = 1
            while( N>=2):
                third = first + second
                first , second = second, third
                N -= 1
            return third
    #方法二:遞迴
    class Solution:
        def fib(self, N: int) -> int:
            if N < 2:
                return N
            return self.fib(N-1) + self.fib(N-2)
    #方法三:遞迴,剪枝減少重複計算
    class Solution:
        def fib(self, N: int) -> int:
            if N <= 1:
                return N
            # self.cache = {}
            # if N-1 in self.cache.keys():
            #     pre = self.cache[N-1]
            # else:
            #     pre = self.fib(N-1)
            #     self.cache[N-1] = pre
            # if N-2 in self.cache.keys():
            #     ppre = self.cache[N-2]
            # else:
            #     ppre = self.fib(N-2)
            #     self.cache[N-2] = ppre
            # return pre + ppre
            self.cache = {0:0,1:1}
            return self.filter(N)
        def filter(self, N: int) -> int:
            if N in self.cache.keys():
                return self.cache[N]
            self.cache[N] = self.filter(N-1)+self.filter(N-2)
            return self.filter(N)
    
  • 問題:一隻青蛙一次可以跳上1級臺階,也可以跳上2級。求該青蛙跳上一個n級的臺階總共有多少種跳法(先後次序不同算不同的結果)。

  • 解決:

    #動態規劃dp
    #1.定義狀態:f(n):青蛙跳上第n級臺階的總跳法
    #2.轉移方程:f(n) = f(n+1) + f(n+2)
    #3.設定初始值:f(0) = 1 , f(1) = 1, f(2) = 2
    class Solution:
        def jumpFloor(self, number):
            dp = {0:1, 1:1}
            for i in range(2,number+1):
                dp[i] = dp[i-1] + dp[i-2]
            return dp[number]