Problem
On a staircase, cost[i] represents the cost of the I-ladder, as long as you pay the price you can climb one or two steps, you can start from index 0 or index 1 to crawl. The minimum price to climb to the top (the cost index from 0 to n-1, to climb to the ladder on Index N). The cost is at least 2 of the length.
Ideas
Procedure 1: Dp[i] represents the minimum cost to reach the I ladder, as one or two steps can be skipped, dp[i] can represent the minimum value of the cost of jumping over the previous ladder and jumping over the first two steps, the DP formula is:\ (Dp[i] = min (dp[ I-1]+cos[i-1], dp[i-2]+cost[i-2]) \)
Time complexity O (n), spatial complexity O (n)
Procedure 2: Considering that the value of each DP Dp[i] depends only on the previous two values dp[i-1] and dp[i-2], you can use two temporary variables F1 and F2 instead, which saves the space overhead of the DP array.
Time complexity O (n), Spatial complexity O (1)
Code
Procedure 1:
class Solution(object): def minCostClimbingStairs(self, cost): """ :type cost: List[int] :rtype: int """ dp = [0] * (len(cost)+1) 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[len(cost)]
Procedure 2:
class Solution(object): def minCostClimbingStairs(self, cost): """ :type cost: List[int] :rtype: int """ f1 = f2 = 0 for i in range(2,len(cost)+1): f1, f2 = min(f1+cost[i-1], f2+cost[i-2]), f1 return f1
746. Min Cost Climbing stairs