首页 > 编程语言 >38天【代码随想录算法训练营34期】第九章 动态规划part01 (● 理论基础 ● 509. 斐波那契数 ● 70. 爬楼梯 ● 746. 使用最小花费爬楼梯)

38天【代码随想录算法训练营34期】第九章 动态规划part01 (● 理论基础 ● 509. 斐波那契数 ● 70. 爬楼梯 ● 746. 使用最小花费爬楼梯)

时间:2024-04-28 18:22:25浏览次数:16  
标签:契数 爬楼梯 int self 随想录 cost return dp

理论基础

  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]

标签:契数,爬楼梯,int,self,随想录,cost,return,dp
From: https://www.cnblogs.com/miramira/p/18164264

相关文章