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:
Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
Example 2:
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
Note:
cost will have a length in the range [2, 1000].
Every cost[i] will be an integer in the range [0, 999].
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-cost-climbing-stairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的思路:
1. dp[i]表示上到第i个台阶所花的最小费用:
dp[i] = min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]),上到第i层取决于是上了一个台阶还是上了两个台阶,上一个台阶,则cost[i-1]肯定是要花费的,上两个台阶,肯定cost[i-2]是要花费的。
2.因为是花完才能上台阶,所以dp[0] = dp[1] = 0;
3. 数组要开的比cost数组大一个,因为我们要取到上到顶的台阶
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int size = cost.size();
vector<int> dp(size+1, 0);
dp[0] = dp[1] = 0;
for(int i = 2; i <= size; i++){
dp[i] = min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]);
}
return dp[size];
}
};