45. Jump Game II

来源:互联网 发布:做报刊的软件 编辑:程序博客网 时间:2024/06/05 08:59

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.

转载出处: 点击打开链接

当前i所在的位置,下一次所能跳的最远处是nums[i]+i,类似于BFS的想法,从起点开始,把它所有能到的点都算完,再进行下一跳。如果在当前跳所能到达的最大范围能到结尾,结束。当前的跳数必定是最少的。

 int jump(vector<int>& nums) {       int n=nums.size();       if(n<=1) return 0;       int level=0,i=0,curmax=0,nextmax=0;       while(1)       {           level++;           for(;i<=curmax;i++)//当前能跳的范围           {              nextmax=max(nextmax,nums[i]+i);              if(nextmax>=n-1)              return level;           }           curmax=nextmax;       }       return 0;    }


0 0
原创粉丝点击