【思路】
简单的一维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]);
}
}