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])