LeetCode746. Min Cost Climbing Stairs 使用最小花费爬楼梯

题目描述:

数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。

每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。

您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。

示例 1:

输入: cost = [10, 15, 20] 输出: 15 解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。

 示例 2:

输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] 输出: 6 解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。

注意:

  1. cost 的长度将会在 [2, 1000]。
  2. 每一个 cost[i] 将会是一个Integer类型,范围为 [0, 999]。

 

解题思路:

第一个想法是使用递归,即递归穷举得到所有的走法,然后比较得到最小值即可。

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int stat = 0;
        int temp = 0;
        int []res = new int[1];
        res[0] = Integer.MAX_VALUE;
        countCost(stat, cost, temp, res);
        temp = 0;
        countCost(stat+1, cost, temp, res);
        return res[0];
    }
    public int countCost(int stat, int[] cost, int temp, int[] res){
        if(stat > cost.length)
            return 0;
        if(stat == cost.length){
            if(temp < res[0])
                res[0] = temp;
            return 0;
        }
        if(stat == cost.length-1){
            temp += cost[stat];
            if(temp < res[0])
                res[0] = temp;
            return 0;
        }
        temp += cost[stat];
        return countCost(stat+1, cost, temp, res)+countCost(stat+2, cost, temp, res);
    }
}

代码倒是没有问题,不过在OJ中会超时emmmmmm。

 

第二个想法自然是动态规划,可以很清楚的发现动态转移规律:

用dp[i] 表示爬 i 个台阶所需要的成本,所以dp[0]=0,dp[1]=0

每次爬 i 个楼梯,计算的都是从倒数第一个结束,还是从倒数第二个结束,由此可以总结动态转移方程为

dp[i] = min{dp[i-2]+cost[i-2] , dp[i-1]+cost[i-1]};

 

因此代码为:

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int len = cost.length;
        if(len <= 0)
            return 0;
        if(len == 1)
            return cost[0];
        if(len == 2)
            return Math.min(cost[0],cost[1]);
        int[] dp = new int[len+1];
        dp[0] = 0;
        dp[1] = 0;
        for(int i=2; i<=len ;i++){
            dp[i] = Math.min(dp[i-2]+cost[i-2], dp[i-1]+cost[i-1]);
        }
        return dp[len];
    }
}

时间复杂度为O(n),空间复杂度为O(n)。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值