746. Min Cost Climbing Stairs [Easy]

【思路】

简单的一维dp

每个位置由前两个位置的值确定,因此可以空间优化不需要dp数组存储

可以用动态规划,也可以用recursion + mem(仅recursion会Time Limit Exceeded)

【两种dp】

本题dp的值可以是到达当前位置的总cost,则最终结果为dp[cost.length]

也可以是经过当前位置的总cost,则最终结果为Math.min(dp[cost.length - 1], dp[cost.length - 2])

自己的思路是前者,后者可以参考后两段代码,最简短的代码是这个思路

// recursion + mem
class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int[] mem = new int[cost.length + 1];
        return helper(cost, mem, cost.length);
    }
    private int helper(int[] cost, int[] mem, int index) {
        if (index == 0 || index == 1)
            return 0;
        if (mem[index] != 0)
            return mem[index];
        mem[index] = Math.min(helper(cost, mem, index - 1) + cost[index - 1], helper(cost, mem, index - 2) + cost[index - 2]);
        return mem[index];
    }
}
// 用dp数组的动态规划
class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int height = cost.length + 1;
        int[] dp = new int[height];
        for (int i = 2; i <= cost.length; i++)
            dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
        return dp[height - 1];
    }
}
// 不用dp数组的动态规划(动态规划的空间优化)
class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int pp = 0, p = 0, curr = 0;
        for (int i = 2; i <= cost.length; i++) {
            curr = Math.min(pp + cost[i - 2], p + cost[i - 1]);
            pp = p;
            p = curr;
        }
        return curr;
    }
}
// 无dp数组的动态规划,经过当前位置的总cost思路
class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int pp = cost[0], p = cost[1];
        for (int i = 2; i < cost.length; i++) {
            int curr = Math.min(pp, p) + cost[i];
            pp = p;
            p = curr;
        }
        return Math.min(pp, p);
    }
}
// 最简短的代码,直接修改cost数组,经过当前位置的总cost思路
class Solution {
    public int minCostClimbingStairs(int[] cost) {
        for (int i = 2; i < cost.length; i++)
            cost[i] += Math.min(cost[i - 1], cost[i - 2]);
        return Math.min(cost[cost.length - 1], cost[cost.length - 2]);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值