leetcode 746 min cost climbing stairs

746. Min Cost Climbing Stairs


On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).

Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.

Example 1:

1
2
3
Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.

Example 2:

1
2
3
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].

Note:

  1. cost will have a length in the range [2, 1000].
  2. Every cost[i] will be an integer in the range [0, 999].

动态规划问题

定义一个dp[n],表示在包含n个阶梯的cost时,最小的总cost。

dp[i] = min( dp[i-1]+cost[i] , dp[i-2]+cost[i]),对于第i个阶梯,可以从第i-1个阶梯或者是第i-2个阶梯过来,

最终返回的时第n个阶梯和第n-1个阶梯中cost小的那一个,返回max(dp[n], dp[n-1])。


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

solution区域更简洁的版本:

空间开销更小,达到了O(1)

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int minCostClimbingStairs(int[] cost) {
int f1 = 0, f2 = 0;
for (int i = cost.length - 1; i >= 0; --i) {
int f0 = cost[i] + Math.min(f1, f2);
f2 = f1;
f1 = f0;
}
return Math.min(f1, f2);
}
}
1
2
3
4
5
6
class Solution(object):
def minCostClimbingStairs(self, cost):
f1 = f2 = 0
for x in reversed(cost):
f1, f2 = x + min(f1, f2), f1
return min(f1, f2)