week16
题目
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.
Note:
1. cost will have a length in the range [2, 1000].
2. Every cost[i] will be an integer in the range [0, 999].
原题地址:https://leetcode.com/problems/min-cost-climbing-stairs/description/
解析
题目要求给定每一阶楼梯阶梯的代价,每次可以走一层或两层,求从最底部爬到最顶部的最小代价。
思路:该题属于动态规划问题,给定一个爬楼梯方案,对于某一级的阶梯,我们只可以选择走或者不走。我们可以用一个sum[n][2]的数组保存到每一阶楼梯时选择走该级阶梯的最小总代价以及不走该级阶梯的最小总代价。则我们可以得到每一阶阶梯的公式:
不走该级阶梯的最小代价为sum[i][0]=sum[i - 1][1],即该级阶梯不走,则上一级阶梯必须走。
走该级阶梯的最小代价为sum[i][1]=min(sum[i - 1][0] + cost[i], sum[i - 1][1] + cost[i]),即该级阶梯走,则上一级阶梯可走可不走,取二者中的较小者。
最后得到的最高级阶梯中的两者中较小的一个即为答案。
代码
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int length = cost.size();
if (length == 0) {
return 0;
}
int** sum = new int*[length];
for (int i = 0; i < length; ++i) {
sum[i] = new int[2];
}
sum[0][0] = 0;
sum[0][1] = cost[0];
for (int i = 1; i < length; ++i) {
sum[i][0] = sum[i - 1][1];
sum[i][1] = min(sum[i - 1][0] + cost[i], sum[i - 1][1] + cost[i]);
}
return min(sum[length - 1][0], sum[length - 1][1]);
}
int min(int a, int b) {
return a < b ? a : b;
}
};