You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the minimum cost to reach the top of the floor.
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].
Constraints:
- 2 <= cost.length <= 1000
- 0 <= cost[i] <= 999
自底向上动态规划
创建长度为 n+1 的数组dp,其中 dp[i] 表示达到台阶i花费的最少体力值
由于可以选择下标 0 或 1 作为初始阶梯,因此有dp[0]=dp[1]=0。
上楼梯可以一级上也可以两级上。如果一级上的话dp[i - 1] + cost[i - 1]表示到达i花费的体力值,两级上的话是dp[i - 2] + cost[i - 2],在这两者中取最小值表示上本级台阶所需的最小体力值
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int size = cost.size();
vector<int> dp(size + 1);
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];
}
};