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:

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

c[i]代表到i-th個階梯需要的最小cost。 dp state transition: c[i] = min(c[i - 1] + cost[i - 1], c[i - 2] + cost[i - 2]) 最後所求就是c[n]。

// Dynamic Programming
int minCostClimbingStairs(vector<int>& cost) { // time: O(n); space: O(n)
    int n = cost.size();
    if (n <= 2) return 0;
    vector<int> c(n + 1, 0);
    for (int i = 2; i <= n; ++i) {
        c[i] = min(c[i - 2] + cost[i - 2], c[i - 1] + cost[i - 1]);
    }
    return c.back();
}
// Space Optimized Dynamic Programming
int minCostClimbingStairs(vector<int>& cost) { // time: O(n); space: O(1)
    int n = cost.size();
    if (n <= 2) return 0;
    int two_step = 0, one_step = 0, res = 0;
    for (int i = 2; i <= n; ++i) {
        res = min(two_step + cost[i - 2], one_step + cost[i - 1]);
        two_step = one_step;
        one_step = res;
    }
    return res;
}

這個dp的想法角度稍微不一樣,dp[i]代表由i-th這個階梯跳出去的cost,那每個階梯可以選擇往後跳1或2格。所以最後所求是dp[n - 2]和dp[n - 1]的較小值。 dp state transition: dp[i] = cost[i] + min(dp[i - 1], dp[i - 2])

// Dynamic Programming
int minCostClimbingStairs(vector<int>& cost) { // time: O(n); space: O(n)
    int n = cost.size();
    vector<int> dp(n, 0);
    dp[0] = cost[0];
    dp[1] = cost[1];
    for (int i = 2; i < n; ++i) {
        dp[i] = cost[i] + min(dp[i - 2], dp[i - 1]);
    }
    return min(dp[n - 2], dp[n - 1]);
}
// Space Optimized Dynamic Programming
int minCostClimbingStairs(vector<int>& cost) { // time: O(n); space: O(1)
    int n = cost.size();
    int two_step = cost[0];
    int one_step = cost[1];
    int cur = min(two_step, one_step);
    for (int i = 2; i < n; ++i) {
        cur = cost[i] + min(two_step, one_step);
        two_step = one_step;
        one_step = cur;
    }
    return min(two_step, one_step);
}
70. Climbing Stairs

Last updated

Was this helpful?