题目
题目大意:跳阶梯,选择从第0或者第1级阶梯开始,每次可以向上跳一到两级,问到达阶梯顶部的最小代价。数组元素 cost[i] 表示在第 i 级阶梯向上跳需要花费的代价。
注:这里到达顶部的意思不是指站在最高级阶梯处,需要跳出最高阶。
Example 1:
Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
开始点选择cost[1],花费15代价,跳两级,即可跳出该阶梯
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].
选择的跳点序列为: cost[0] cost[2] cost[4] cost[6] cost[7] cost[9]
思路
使用动态规划
定义状态
dp[i] : 到达第i级阶梯花费的最小总代价
初始化dp[0] = 0,dp[1] = min(cost[1], dp[0] + cost[0])
因为需要跳过最高级阶梯,所以当有n级阶梯(标号0到n-1)时,最终答案是dp[n]
状态转移
dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2])
到达每级阶梯的路径有两条,从两条路径中选择最小总代价作为到达该级的最小总代价
代码
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n = cost.size();
vector<int> dp(n + 1);
dp[0] = 0;
dp[1] = min(dp[0] + cost[0], cost[1]);
for(int i = 0; i < n + 1; i++) {
dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
}
return dp[n];
}
};