Min Cost Climbing Stairs LT746

 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:

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

 

Example 2:

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].

Idea 1. dynamic programming, assume dp[i] is the cost to reach stair i, the relationship is as follow:

dp[i] = min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2])

since the current value dp[i] only depends on the previous two, three variables is enough like Fibnacci sequence, third = min(second + cost[i-1], first + cost[i-2]).

Note the question is not clear, make sure you understand the question and run the test cases before looking for a solution, this one the destination stair is actually one step beyond the last step. Take cost = [10, 15, 20], 

dp[0] = dp[1] = 0

dp[2] = min(0 + cost[0], 0 + cost[1]) = min(10, 15) = 10

the final destionation: dp[3] = min(dp[1] + cost[1], dp[2] + cost[2]) = min(0 + 15, 10 + 20) = 15

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

slightly simplified:

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

Idea 2. Instead of bottom up from left to right, top down dp from right to left:

dp[i] = cost[i] + min(dp[i+1], dp[i+2])

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

 

posted on 2019-05-09 04:54  一直走在路上  阅读(122)  评论(0编辑  收藏  举报

导航