Min Cost Climbing Stairs

Min Cost Climbing Stairs--LeetCode

(原題鏈接:點擊打開鏈接)

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

Solution:

此題主要運用動態規劃的思想。noSelected[i]表示在對第i個數進行選擇時,不選擇這個數的總花費。因爲不選擇這個數時,上一個數就必須被選擇,所以它的值應該應該等於上一次選擇選擇了對應的數的總花費,即hasSelected[i-1]。當一個數準備被選擇時,它上一個是否選擇並不是很重要,所以應當選擇上一步花費比較小的數,所以hasSelected[i]=min(noSelected[i-1],hasSelected[i-1])+cost[i]。

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int length = cost.size();
        int hasSelected[length];
        int noSelected[length];
        noSelected[0] = 0;
        hasSelected[0] = cost[0];
        for(int a = 1; a < length; a++)
        {
            noSelected[a] = hasSelected[a-1];
            hasSelected[a] = min(noSelected[a-1], hasSelected[a-1]) + cost[a];
        }
        return min(noSelected[length-1], hasSelected[length-1]);
    }
};

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