- Min Cost Climbing Stairs
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
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].
Notice
1.cost will have a length in the range [2, 1000].
2.Every cost[i] will be an integer in the range [0, 999].
解法:DP。
代码如下:
class Solution {
public:
/**
* @param cost: an array
* @return: minimum cost to reach the top of the floor
*/
int minCostClimbingStairs(vector<int> &cost) {
int len = cost.size();
if (len == 0) return 0;
vector<int> dp(len, 0);
int result = 0;
dp[0] = cost[0];
dp[1] = cost[1];
for (int i = 2; i < len; ++i) {
dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i];
}
return min(dp[len - 1], dp[len - 2]);
}
};
二刷:
class Solution {
public:
/**
* @param cost: an array
* @return: minimum cost to reach the top of the floor
*/
int minCostClimbingStairs(vector<int> &cost) {
int n = cost.size();
if (n == 0) return 0;
if (n == 1) return cost[0];
vector<int> dp(n + 1, 0); //dp[i] is the cost to reach i-th step (start from 0)
//dp[n] is the result
for (int i = 2; i <= n; i++) {
dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
}
return dp[n];
}
};
三刷:空间复杂度O(1)
class Solution {
public:
/**
* @param cost: an array
* @return: minimum cost to reach the top of the floor
*/
int minCostClimbingStairs(vector<int> &cost) {
int n = cost.size();
if (n == 0) return 0;
if (n == 1) return cost[0];
int prepre = 0, pre = 0, cur = 0;
for (int i = 2; i <= n; i++) {
cur = min(prepre + cost[i - 2], pre + cost[i - 1]);
prepre = pre;
pre = cur;
}
return cur;
}
};