LeetCode Min Cost Climbing Stairs

本文介绍了一个经典的动态规划问题,即如何以最小的成本爬到楼梯的顶部。提供了详细的算法实现,并通过两个实例说明了如何找到最优路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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个阶梯对应着一个非负数的体力花费值 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]

题解:给一个数组,表示每登一级台阶需要花费的成本,每次能登一步或者两步,求登到顶,需要花费的最少的成本?这道题是一道典型的动态规划的题目,甚至都有点类似于贪心算法,先保存该数组起始的第一个成本和第二个成本,因为后续攀登都要从登一步或登两步开始攀登。然后开始计算相应的成本开销。

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++)      //从第3个元素开始
        {
            int curr = cost[i];
            dp[i] = Math.min(dp[i - 1],dp[i - 2]) + curr;   //每次比较当前元素与之前两步的元素中的最小值,其实该动态规划算法有点类似于贪心算法
        }
        return Math.min(dp[cost.length - 1],dp[cost.length - 2]);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值