LeetCode-746-使用最小花费爬楼梯-动态规划

题目描述:
给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。
请你计算并返回达到楼梯顶部的最低花费。

题目链接:LeetCode-746-使用最小花费爬楼梯

解题思路:注释中有详解。

代码实现:

class Solution {
    
    
    public int minCostClimbingStairs(int[] cost) {
    
    
        // 1. 确定 dp[i] 的含义: dp[i]表示爬到第 i 个位置的最小花费
        // 2. 递推公式:dp[i]=Math.min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2])
        //            dp[i-1]:再加上向上跳 1步的花费 cost[i-1]
        //            dp[i-2]:再加向上上跳 2步的花费 cost[i-2]
        // 3. 如何初始化:dp[0]=0; dp[1]=0,因为不需要花费体力,开始爬才会产生花费
        // 4. 遍历的方向:从前向后遍历
        if (cost.length==2){
    
    
            return Math.min(cost[0], cost[1]);
        }

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

猜你喜欢

转载自blog.csdn.net/Miss_croal/article/details/132856831