746. Min Cost Climbing Stairs
https://leetcode.com/problems/min-cost-climbing-stairs/
Easy
问题描述:
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.
Example 1:
1 | Input: cost = [10, 15, 20] |
Example 2:
1 | Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] |
Note:
cost
will have a length in the range[2, 1000]
.- Every
cost[i]
will be an integer in the range[0, 999]
.
题目分析:
这是一道“爬楼梯”的问题,这个楼梯每次可以走一格或者两格,每一格都有对应的花费,从第一格或者第二格的位置出发,我们需要找到登顶时的最低花费。
这一题是一个简单的动态规划问题,有两种走法可以到达第i
格:从第i-1
格出发,或者从第i-2
格出发。因此,到达第i
格的最低花费为:dp[i]=min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2])
,需要注意,第一格和第二格的花费均为0。
代码:
1 | class Solution: |
补充:
上述代码的空间复杂度为O(n)
,可以通过用三个变量保存每一步的花费来减少空间占用,代码如下:
1 | class Solution: |