Leetcode747 Min Cost Climbing Stairs(爬楼梯的最小代价)

33 篇文章 0 订阅
12 篇文章 0 订阅

题目:

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:

  1. cost will have a length in the range [2, 1000].
  2. 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);
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值