1. 程式人生 > >45. Jump Game II

45. Jump Game II

maximum 距離 () nat pan represent TP bsp init

問題描述:

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.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.

Note:

You can assume that you can always reach the last index.

解題思路:

看到求最小的步數,於是我就用了dp,天真如我,超時了:)

記錄一下dp的分析吧

可以用一維dp數組

dp[i]代表從起始點到i點的最小距離。

對每一個元素,我們對它能夠到達的點的dp進行更新:

       for(int j = 1; j <= nums[i]; j++){
                if(i+j >= nums.size())
                    break;
                dp[i+j] = min(dp[i]+1, dp[i+j]);
            }

最後求dp[nums.size()]

然後就超時了,然後我打開相關標簽一看,居然是greedy啊我的朋友們!!!!

代碼:

dp:

class Solution {
public:
    int jump(vector<int>& nums) {
        if(nums.size() < 2)
            return 0;
        vector<int> dp(nums.size(), INT_MAX);
        dp[0] = 0;
        for(int i = 0; i < nums.size(); i++){
            
for(int j = 1; j <= nums[i]; j++){ if(i+j >= nums.size()) break; dp[i+j] = min(dp[i]+1, dp[i+j]); } } return dp[nums.size()-1]; } };

greedy:參考鏈接,圖文解釋

朋友們,神一樣的解法啊!!!

O(n)的復雜度

每次cur是代表最大能到的範圍,last代表上一次能到的範圍,每當i > last 時,要更新可達範圍,以為已經跳出了上一次能走的最大範圍

此時也要更新last到本次能達到的可及範圍,同時增加ret。

class Solution {
public:
    int jump(vector<int>& nums) {
        int ret = 0;
        int last = 0;
        int cur = 0;
        for(int i = 0; i < nums.size(); i++){
            if(i > last){
                last = cur;
                ret++;
            }
            cur = max(cur, i+nums[i]);
        }
        return ret;
    }
};

45. Jump Game II