动态规划:04使用最小花费爬楼梯
五部曲
-
确定dp数组含义:到达第i层的最少花费是d[i]
-
确定递归公式d[i] = min(d[i-1]+cost[i-1],d[i-2]+cost[i-2])
到达d[i]只能有d[i-1]和d[i-2]到达,花费分别是d[i-1]+cost[i-1],d[i-2]+cost[i-2],应该取最小值,即min(d[i-1]+cost[i-1],d[i-2]+cost[i-2])
-
dp数组初始化:d[0]=0,d[1]=0
-
确定遍历顺序:从前往后
因为是模拟台阶,而且dp[i]由dp[i-1]dp[i-2]推出,所以是从前到后遍历cost数组就可以了。但是稍稍有点难度的动态规划,其遍历顺序并不容易确定下来。 例如:01背包,都知道两个for循环,一个for遍历物品嵌套一个for遍历背包容量,那么为什么不是一个for遍历背包容量嵌套一个for遍历物品呢? 以及在使用一维dp数组的时候遍历背包容量为什么要倒序呢?
-
debug->打印dp数组
代码
class Solution {
public int minCostClimbingStairs(int[] cost) {
// if(cost.length < 2) return 0;数组默认值就是0,所以可以不加上
int[] dp = new int[cost.length + 1];
dp[0] = 0;
dp[1] = 0;
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[cost.length];
}
}
- 时间复杂度:O(n)
- 空间复杂度:O(n)
优化空间后
class Solution {
public int minCostClimbingStairs(int[] cost) {
int dp0 = 0;
int dp1 = 0;
for(int i = 2; i <= cost.length; i++) {
int dpi = Math.min((dp1 + cost[i - 1]), (dp0 + cost[i - 2]));
dp0 = dp1;
dp1 = dpi;
}
return dp1;
}
}
- 时间复杂度:O(n)
- 空间复杂度:O(1)
总结
本题相较于动态规划:03爬楼梯难了一点,但整体思路一致