mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
动态规划 爬楼梯最小费率 java 状态压缩优化
This commit is contained in:
@ -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
|
||||
|
||||
动态规划(版本一)
|
||||
|
Reference in New Issue
Block a user