leetcode 746 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.

给定一个数组cost,其中cost[i]的值就代表着你爬第[i]阶的台阶的开销。一旦你付了这个开销,你就可以继续往上爬一阶或者两阶,知道你达到最顶层(数组的结尾元素再多一层)。同时你可以选择从第0阶开始或者第一阶开始。
我们的目标是找出你爬到最顶层所付出的最小的开销。

Example 1:
Input: cost = [10, 15, 20]
Output: 15
Explanation: 最低开销是,从第1阶(15)开始,只花费15就可以到顶层。
Example 2:
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: 最低开销是,从第0阶开始(1),然后只走值为1的台阶,其中跳过第3阶。

想法

  • 动态规划问题。
  • 我们新建一个数组minCost,用它来保存走到第i阶所消耗的最低开销。
  • minCost的长度应该为cost数组长度加一,其中mincost数组的最后一个元素的值就是本题的答案,最低开销。

解法

    public int minCostClimbingStairs(int[] cost) {
        int minCost[] = new int[cost.length+1];
        minCost[0] = cost[0];
        minCost[1] = cost[1];
                
        for(int i=2;i<=cost.length;i++){
            int costV = (i == cost.length) ? 0 : cost[i];
            minCost[i] = Math.min(minCost[i-1]+costV, minCost[i-2]+costV);
        }
        
        return minCost[cost.length];
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值