题目:
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].
Note:
cost
will have a length in the range[2, 1000]
.- Every
cost[i]
will be an integer in the range[0, 999]
.
先分析一下整个过程,在i-th阶梯上,下一步可以是i+1-th,也可以是i+2-th,即两种选择,而选择哪一种,是比较由i+1阶梯到达顶端的代价和由i+2阶梯到达顶端的代价的大小决定的,选择代价小的那一阶作为下一步。我们可以逆向迭代地考虑这个问题,逆向得到每一阶到达顶端的代价,从最高阶cost.length-1开始,确定其到达顶端的代价,那么为cost[cost.length-1],向前推导,那么cost.length-2阶的代价为cost[cost.length -2],而对于cost.length - 3阶来说,其可以通过cost.length -2,到达顶端,也可以先跳到cost.length -1再到达顶端,所以要选择二者最小的那一个。即i-th的代价f(i)为:f(i) = cost[i] + min(f(i+1),f(i+2));而同时要注意第0阶和第1阶的情况,由于没有-1阶(用户相当于从-1阶的位置开始),所以上述的解决方法中,实际是没有考虑对f(0)和f(1)的比较的,所以最后不要忘记对第0阶和第1阶的比较。
代码:
java实现
class Solution {
public int minCostClimbingStairs(int[] cost) {
int f1,f2,temp,len;
len = cos.length;//楼梯总阶数
f1 = cost[len -2];
f2 = cost[len -1];
for(int i = cost.length-3;i>-1;i--){
temp = f1;
f1 = cost[i] + Math.min(f1,f2);
f2 = temp;
}
return Math.min(f1,f2);//f1最终会存放f[0],f2最终存放f[1]
}
}
js实现
/**
* @param {number[]} cost
* @return {number}
*/
var minCostClimbingStairs = function(cost) {
var f1,f2,len,tem;
len = cost.length;
f1 = cost[len -2];
f2 = cost[len -1];
for(i = len -3;i>-1;i--)
{
temp = f1;
f1 = cost[i] + Math.min(f1,f2);
f2 = temp;
}
return Math.min(f1,f2);
};