38天【程式碼隨想錄演算法訓練營34期】第九章 動態規劃part01 (● 理論基礎 ● 509. 斐波那契數 ● 70. 爬樓梯 ● 746. 使用最小花費爬樓梯)

MiraMira發表於2024-04-28

理論基礎

  1. 斐波那契數
class Solution:
    def fib(self, n: int) -> int:
        if n == 0:
            return 0
        if n == 1:
            return 1
        return self.fib(n-1)+self.fib(n-2)
  1. 爬樓梯
class Solution:
    def climbStairs(self, n: int) -> int:
        if n <= 1:
            return n
        dp = [0] * 3
        dp[1] = 1
        dp[2] = 2
        total = 0

        for i in range(3, n+1):
            total = dp[1] + dp[2]
            dp[1] = dp[2]
            dp[2] = total
        
        return dp[2]
  1. 使用最小花費爬樓梯
class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        dp = [0] *(len(cost) + 1)
        dp[0] = 0
        dp[1] = 0

        for i in range(2, len(cost)+1):
            dp[i] = min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2])
        
        return dp[-1]

相關文章