《Leetcode of December》746. 使用最小花费爬楼梯

class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        if not cost:
            return 0
        if len(cost)<3:
            return cost[0]
        dp=[0]*len(cost)
        dp[0]=cost[0]
        dp[1]=cost[1]
        for i in range(2,len(cost)):
            dp[i]=cost[i]+min(dp[i-1],dp[i-2])
        return min(dp[-1],dp[-2])
        
        #优化版本,只保存前一个和前两个的状态量就可以了
        a,b = cost[0],cost[1]
        for i in range(2,len(cost)):
            a,b = b,cost[i]+min(a,b)
            # tmp = cost[i]+min(a,b)
            # a=b
            # b=tmp
             
        return min(a,b)

总结:题目不难,就是简单的动态规划,状态转移方程,主要需要注意的就是不是跳到最后一层而是跳到楼顶。 

猜你喜欢

转载自blog.csdn.net/weixin_37724529/article/details/111468743