[Leetcode 45] Jump Game II

来源:互联网 发布:网络记账本 编辑:程序博客网 时间:2024/05/19 17:59
  • Question
    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.)
  • 思路
    第一眼看到这个题,我首先想到用深度搜索找出能到达终点的所有路径,进而得到最短的那条。 不用说,这是一个蠢办法,超时了。

    然后想到了动态规划的方法。 建立一个辅助数组A,A[i] 保存从0到i需要跳的次数。但是这个方法遇到超大的数据案例还是过不了(这个案例的数据放在word里有37页,醉了)。

    找到的原因: 第k个元素能到达的元素为 k+1, k+2, …, nums[k]+k, 我每个元素都访问了一遍,这造成了无用的时间开销。 要保证跳数最少, 不需要每个元素访问一遍,只需要从k+1, k+2, …, nums[k]+k 中 k+n+nums[k+n](1<= n<= nums[k]+k )最大的作为下一跳就可以了。

    例如 [2,1,3,1,4], 第0个元素能到达的元素 为nums[1]=1, nums[2]=3,到达nums[1],nums[2]都只需要一跳。而nums[1]能跳到的最远的范围nums[2]也能跳到,所以我们不需要访问nums[1] , 下一跳只需要访问nums[2] 就可以了。

  • 代码如下

class Solution {public:    int jump(vector<int>& nums) {        int len=nums.size();        if(nums.size()<2) return 0;        vector<int> A(len,0);        for(int i=0; i<len; ){            int temp=i+nums[i];            int k=i, temp2=0;            for(int j=i+1; j<len && j<=temp; ++j){                if(A[j]==0) A[j]=A[k]+1;                //找到下一跳的位置                if(temp2 <= j+nums[j]){                      i=j;                    temp2=j+nums[j];                }             }            if(A[len-1] != 0) break;        }        return A[len-1];    }};