Dynamic Programming——No.746 Min Cost Climbing Stairs

本文探讨了爬楼梯问题,即在每一层楼梯都有不同成本的情况下,如何从底部到达顶部花费最少的钱。通过动态规划方法,我们找到了一个高效的解决方案,该方案从两个可能的起点开始,并在每一步都选择成本较低的路径。

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

Problem:

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.

Explanation:

爬完楼梯需要n步,每次能爬1或2步,每一层楼梯都需要支付一定费用才能继续爬,可以从第一个或第二个楼梯开始爬,求花钱最少的方法。

My Thinking:

对于每一个台阶,如果要经过他,就必须走过他前一个或前前一个台阶,因此到此台阶需要花费的最少钱应该是前一个与前前一个台阶之前花费最少钱的最小值,因此有bp[i]=Math.min(bp[i-1],bp[i-2])+cost[i]

My Solution:

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

Optimum Thinking:

Optimum Solution:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值