Jump 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.)

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

首先第一個版本(最先想到,最天真的解法):

class Solution {
public:
    int Trackjump(vector<int>& nums, int cur)
    {
        if (cur == nums.size() - 1)
            return 0;
        int min = nums.size();
        for (int i = 1; i <= nums[cur] && cur + i<nums.size(); ++i)
        {
            int temp = Trackjump(nums, cur + i) + 1;
            if (temp < min)
                min = temp;
        }
        return min;
    }
    int jump(vector<int>& nums) {
        if (nums.size() <= 0)
            return 0;
        return Trackjump(nums, 0);
    }
};

當然是沒有通過,當測試用例20左右長度時就會超時,單純遞歸計算了太多的重複信息。
第二種,改進後的遞歸,記錄已計算的值:

class Solution {
public:
    int Trackjump(vector<int>& nums,int cur,vector<vector<int>>& record)
    {
        if(cur == nums.size()-1)
            return 0;
        int min = nums.size();
        for(int i=1;i<=nums[cur] &&cur+i<nums.size();++i)
        {
            int temp;
            if(record[cur][i] == 0)
            {
                temp = Trackjump(nums,cur+i,record)+1;
                record[cur][i] = temp;
            }
            else
            {
                temp = record[cur][i];
            }
            if(temp < min)
            {
                min=temp;

            }
        }
        return min;
    }
    int jump(vector<int>& nums) {

        if(nums.size() <= 0)
            return 0;
        int l = nums.size();
        vector<vector<int>> record(l);
        for(int i=0;i<l;++i)
            record[i].resize(l);
        return Trackjump(nums,0,record);
    }
};

本以爲這個穩過了,結果還是倒在最後第二個測試用例上面,也是就長度極長的全1序列,遞歸的函數調用浪費了大量的空間和時間。
以此來看必須使用循環,同時降低算法複雜度。

class Solution {
public:

    int jump(vector<int>& nums) {
        int jumps = 0,curEnd =0,curFarthest=0;
        for(int i=0;i<nums.size()-1;++i)
        {
            curFarthest = max(curFarthest,i+nums[i]);
            if(i==curEnd)
            {
                jumps++;
                curEnd = curFarthest;
            }
        }
        return jumps;
    }
};

最終的解法O(n)。

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