0%

LeetCode-746

题目

Snipaste_2020-12-21_13-29-47.png

结果

Snipaste_2020-12-21_13-33-08.png

代码

DP

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int minCostClimbingStairs(int[] cost) {
int[] dp = new int[cost.length];
dp[0] = cost[0];
dp[1] = cost[1];
for (int i = 2; i < dp.length; i++) {
dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
}
return Math.min(dp[dp.length - 1], dp[dp.length - 2]);
}
}

改进的DP

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int minCostClimbingStairs(int[] cost) {
int x = cost[0];
int y = cost[1];
for (int i = 2; i < cost.length; i++) {
int cur = Math.min(x, y) + cost[i];
x = y;
y = cur;
}
return Math.min(x, y);
}
}

复杂度

时间复杂度:O(n)

空间复杂度:O(1)