貪心算法的使用

      貪心算法(又稱貪婪算法)是指,在對問題求解時,總是做出在當前看來是最好的選擇。也就是說,不從整體最優上加以考慮,他所做出的是在某種意義上的局部最優解

       既然貪心總是在求局部最優,所有使用貪心要首先判斷,我每次求局部最優,最後能不能達到全局最優。如果是,那麼就可以使用貪心算法了。

45Jump Game II

題目描述:

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)


題目解析:

1. 此題的意思是:arr中的每一個數字表示從當前位置可以最遠向後走幾步,題目求的是:從第一個位置出發,最短需要幾步到最後一個位置。

2. 做着一道題時:到了一個新的位置i:考慮的是下一步最遠到哪個位置肯定是i+arr[i]。那麼前進一步,下一次就是在i到i+arr[i]中找尋下一個最遠能到達的位置。直到某一步到了最末端位置。考慮在到達第一次能夠直接下一步到達最末位置的哪個位置j時,0到j位置我們都是有計算遍歷過的,所以不會錯過最優解,並且沒走一步,找的都是最遠到達的位置。所以這樣的貪心出來的結果也是全局最優解。那麼就可以使用貪心算法。


代碼如下:

class Solution {
public:
    // 使用貪心算法來解決
    int jump(vector<int>& nums) 
    {
        if(nums.empty())
            return 0;
        // 使用cur來記錄當前步的最遠到達位置,使用pre來記錄上一步最遠到達的位置
        int cur = 0, pre = 0;
        // res爲需要走的步數
        int res = 0;
        int i=0;
        while(cur < nums.size()-1)
        {
            pre = cur;
            while(i <= pre)
            {
                // 尋找這一步中最遠可以到達的位置
                cur = cur < nums[i] +i ? nums[i] +i : cur;
                ++i;
            }
            // 步數+1
            ++res;
            // 加上pre==cur判斷,如果上一步和這一步走的最遠位置一樣,說明不能到達更遠了,結束了。
            if(pre == cur) 
                return -1;
        }
        
        return res;
        
    }
};

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