LeetCode-746

使用最小花费爬楼梯

代码:

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int[] dp = new int[cost.length + 1];
        dp[0] = 0;
        dp[1] = cost[0];

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

20201221131948

完整测试代码:

public class P746 {

    public int minCostClimbStairs(int[] cost) {
        int[] dp = new int[cost.length + 1];
        dp[0] = 0;
        dp[1] = cost[0];

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

    public static void main(String[] args) {
        P746 p746 = new P746();
        int[] cost = {10, 15, 20};
        int[] cost2 = {1, 100, 1, 1, 1, 100, 1, 1, 100, 1};
        System.out.println(p746.minCostClimbStairs(cost));
        System.out.println(p746.minCostClimbStairs(cost2));
    }
}
posted @ 2020-12-21 13:21  模糊计算士  阅读(65)  评论(0编辑  收藏  举报