其他分享
首页 > 其他分享> > 746. Min Cost Climbing Stairs

746. Min Cost Climbing Stairs

作者:互联网

On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).

Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.

可以从0或者1层开始走,每次可以选择走一层或者两层,代价是当前位置的cost

动态规划dp[i]表示从0或1楼走到第i层的时候,再往上走的最小的代价,转移方程dp[i] = min(dp[i - 1] , dp[i - 2]) + cost[i]

最后答案就是最后一层和倒数第二层,再往上走的最小代价的最小值。min(dp[n - 1], dp[n - 2])

class Solution(object):
    def minCostClimbingStairs(self, cost):
        """
        :type cost: List[int]
        :rtype: int
        """
        n = len(cost)
        dp = [0] * (n)
        dp[0] = cost[0]
        dp[1] = cost[1]
        for i in range(2, n, 1):
            dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
        return min(dp[n - 1], dp[n - 2])

 

标签:index,cost,min,int,step,Cost,Climbing,Stairs,dp
来源: https://www.cnblogs.com/whatyouthink/p/13254194.html