mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #1628 from zhicheng-lee/zhicheng-lee-patch-8
更新 0746.使用最小花费爬楼梯.md Java代码
This commit is contained in:
@ -66,7 +66,7 @@
|
||||
|
||||
所以初始化代码为:
|
||||
|
||||
```
|
||||
```CPP
|
||||
vector<int> dp(cost.size());
|
||||
dp[0] = cost[0];
|
||||
dp[1] = cost[1];
|
||||
@ -201,15 +201,32 @@ public:
|
||||
|
||||
|
||||
### Java
|
||||
|
||||
```Java
|
||||
// 方式一:第一步支付费用
|
||||
class Solution {
|
||||
public int minCostClimbingStairs(int[] cost) {
|
||||
if (cost == null || cost.length == 0) {
|
||||
return 0;
|
||||
}
|
||||
if (cost.length == 1) {
|
||||
return cost[0];
|
||||
int len = cost.length;
|
||||
int[] dp = new int[len + 1];
|
||||
|
||||
// 从下标为 0 或下标为 1 的台阶开始,因此支付费用为0
|
||||
dp[0] = 0;
|
||||
dp[1] = 0;
|
||||
|
||||
// 计算到达每一层台阶的最小费用
|
||||
for (int i = 2; i <= len; i++) {
|
||||
dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]);
|
||||
}
|
||||
|
||||
return dp[len];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```Java
|
||||
// 方式二:第一步不支付费用
|
||||
class Solution {
|
||||
public int minCostClimbingStairs(int[] cost) {
|
||||
int[] dp = new int[cost.length];
|
||||
dp[0] = cost[0];
|
||||
dp[1] = cost[1];
|
||||
|
Reference in New Issue
Block a user