动态规划 爬楼梯最小费率 java 状态压缩优化

This commit is contained in:
yangzhaoMP
2024-03-06 11:41:56 +08:00
parent 3bc9d8eb56
commit 571ddaa69d

View File

@ -244,6 +244,24 @@ class Solution {
}
```
```Java
// 状态压缩,使用三个变量来代替数组
class Solution {
public int minCostClimbingStairs(int[] cost) {
// 以下三个变量分别表示前两个台阶的最少费用、前一个的、当前的。
int beforeTwoCost = 0, beforeOneCost = 0, currentCost = 0;
// 前两个台阶不需要费用就能上到因此从下标2开始因为最后一个台阶需要跨越所以需要遍历到cost.length
for (int i = 2; i <= cost.length; i ++) {
// 此处遍历的是cost[i - 1],不会越界
currentCost = Math.min(beforeOneCost + cost[i - 1], beforeTwoCost + cost[i - 2]);
beforeTwoCost = beforeOneCost;
beforeOneCost = currentCost;
}
return currentCost;
}
}
```
### Python
动态规划(版本一)