题目:
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].
题目分析:
题目意思是给定一个cost序列,然后每次可以使用这个花费走一步或两步,直到到达最后。可以从第0个cost开始或者第一个cost开始
我们可以使用动态规划的思路,用一个dp[i]保存从开始到i所需要的总cost,由于一次可以走一步或两步,所以我们从开始到i的花费是取dp[i-1]+cost[i-1] 和 dp[i-2]+cost[i-2]中的小值,边界条件是dp[0]=0和dp[1]=0,可以验证dp[2] = min(cost[0], cost[1]), dp[3] = min(cost[2]+dp[2], cost[1]+dp[1]),符合上面的式子,因此证明这个思路是可以的。
c++代码:
class Solution {
public:
int min(int a, int b) {
if (a < b) return a;
else return b;
}
int minCostClimbingStairs(vector<int>& cost) {
int si = cost.size();
if (si == 0) return 0;
if (si == 1) return cost[0];
int* dp = new int[si];
dp[0] = 0;
dp[1] = 0;
for (int i = 2; i < si; i++) {
dp[i] = min(dp[i-2] + cost[i-2], cost[i-1] + dp[i-1]);
}
return min(dp[si-2]+cost[si-2], dp[si-1]+cost[si-1]);
}
};