[LeetCode] 746. Min Cost Climbing Stairs

原题链接: https://leetcode.com/problems/min-cost-climbing-stairs/

Climbing Stairs专题相关题目

70. Climbing Stairs
746. Min Cost Climbing Stairs

1. 题目介绍

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,数组中存储的值是到达这个位置必须付的费用。
当到达数组中某个位置时,比如第 i 个位置时,首先需要交费cost[ i ],然后可以选择去往i+1或者i+2的位置。
起点是cost[ 0 ]或者cost[ 1 ],每一次可以走1步或者走2步。

求最终走完整个数组时,最小的花费。

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].

2. 解题思路

2.1 动态规划法

我们可以这样想,当到达位置 i 时,最后一步是如何走的呢?只有两种情况;

  1. 从位置 i-2 一次走2步到达位置 i
  2. 从位置 i-1 分两次走1步到达位置 i

那么到达位置 i-2 和位置 i-1的花费中取较小的一个,加上cost[ i ]就是到达位置 i 的最小花费了。
于是我们可以构造一个一维数组dp[ length ] ,dp[ i ] 代表到达位置 i 的最小花费。

递推公式为:
d p [ i ] = m i n ( d p [ i − 2 ] , d p [ i − 1 ] ) + c o s t [ i ] dp[ i ] = min(dp[ i-2 ] , dp[ i-1 ]) + cost[i] dp[i]=min(dp[i2],dp[i1])+cost[i]
需要给最前面的两个dp[ i ]赋初值,dp[0] = cost[0], dp[1] = cost[1].

实现代码

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int length = cost.length;
        int[] dp = new int [length];
        dp[0] = cost[0];
        dp[1] = cost[1];
        for(int i=2;i<length;i++) {
        	dp[i] = (dp[i-1]<dp[i-2]?dp[i-1] :dp[i-2])+ cost[i];
        }
      
        return (dp[length-1]<dp[length-2] ? dp[length-1] : dp[length-2]);
    }
}

2.2 进一步改进:用变量代替一维数组

仔细观察上述方法的实现代码,我们可以发现,每次更新dp[ i ]的时候,只用到了dp[ i-2 ]和dp[ i-1 ]的值,并没有用到dp数组的其他值。因此我们可以抛弃一维数组,只用两个变量存储dp[ i-2 ]和dp[ i-1 ]的值,然后使用第三个变量存储dp[ i ]的值。三个变量交替更新,可以代替一维数组。

实现代码

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int length = cost.length;
        
        int a = cost[0];
        int b = cost[1];
        int c;
        for(int i=2;i<length;i++) {
        	c = ( a<b ? a : b) + cost[i];
        	a = b;
        	b = c;
        }
      
        return ( a<b ? a : b);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值