746. Min Cost Climbing Stairs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int minCostClimbingStairs(int[] cost) {
int n = cost.length;

// 定义 dp[i] 为爬上 cost[i] 的最低花费,使用 n + 1 是将楼梯顶部纳入,便于返回结果
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 0; // 注意题目说明了可以从下标为 1 的台阶开始爬

for (int i = 2; i < dp.length; i++) {
dp[i] = Math.min(dp[i - 2] + cost[i - 2], dp[i - 1] + cost[i - 1]);
}

return dp[n];
}
}

References

746. Min Cost Climbing Stairs
剑指 Offer II 088. 爬楼梯的最少成本