LeetCode 746. Min Cost Climbing Stairs(動態規劃)

題目

題目地址

題目大意:跳階梯,選擇從第0或者第1級階梯開始,每次可以向上跳一到兩級,問到達階梯頂部的最小代價。數組元素 cost[i] 表示在第 i 級階梯向上跳需要花費的代價。

注:這裏到達頂部的意思不是指站在最高級階梯處,需要跳出最高階。

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

    開始點選擇cost[1],花費15代價,跳兩級,即可跳出該階梯

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

    選擇的跳點序列爲: cost[0] cost[2] cost[4] cost[6] cost[7] cost[9]

思路

使用動態規劃

定義狀態

dp[i] : 到達第i級階梯花費的最小總代價

初始化dp[0] = 0,dp[1] = min(cost[1], dp[0] + cost[0])

因爲需要跳過最高級階梯,所以當有n級階梯(標號0到n-1)時,最終答案是dp[n]

狀態轉移

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

到達每級階梯的路徑有兩條,從兩條路徑中選擇最小總代價作爲到達該級的最小總代價

代碼

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int n = cost.size();
        vector<int> dp(n + 1);

        dp[0] = 0;
        dp[1] = min(dp[0] + cost[0], cost[1]);

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

        return dp[n];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章