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

分析:

先分析一下整個過程,在i-th階梯上,下一步可以是i+1-th,也可以是i+2-th,即兩種選擇,而選擇哪一種,是比較由i+1階梯到達頂端的代價和由i+2階梯到達頂端的代價的大小決定的,選擇代價小的那一階作爲下一步。我們可以逆向迭代地考慮這個問題,逆向得到每一階到達頂端的代價,從最高階cost.length-1開始,確定其到達頂端的代價,那麼爲cost[cost.length-1],向前推導,那麼cost.length-2階的代價爲cost[cost.length -2],而對於cost.length - 3階來說,其可以通過cost.length -2,到達頂端,也可以先跳到cost.length -1再到達頂端,所以要選擇二者最小的那一個。即i-th的代價f(i)爲:f(i) = cost[i] + min(f(i+1),f(i+2));而同時要注意第0階和第1階的情況,由於沒有-1階(用戶相當於從-1階的位置開始),所以上述的解決方法中,實際是沒有考慮對f(0)和f(1)的比較的,所以最後不要忘記對第0階和第1階的比較。

代碼:

java實現

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int f1,f2,temp,len;
        len = cos.length;//樓梯總階數
        f1 = cost[len -2];
        f2 = cost[len -1];
        for(int i = cost.length-3;i>-1;i--){
            temp = f1;
            f1 = cost[i] +  Math.min(f1,f2);
            f2 = temp;
        }
        
        return Math.min(f1,f2);//f1最終會存放f[0],f2最終存放f[1]
    }
    
}

js實現

/**
 * @param {number[]} cost
 * @return {number}
 */
var minCostClimbingStairs = function(cost) {
    var f1,f2,len,tem;
    len = cost.length;
    f1 = cost[len -2];
    f2 = cost[len -1];
    for(i = len -3;i>-1;i--)
    {
        temp = f1;
        f1 = cost[i] + Math.min(f1,f2);
        f2 = temp;
    }
    
    return Math.min(f1,f2);
};



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