Title Description:
Given an array of non-negative integers, you is initially positioned at the first index of the array.
Each element of the array represents your maximum jump length is 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 and then 3 steps to the last index.)
Note:
You can assume so can always reach the last index.
This problem is greedy idea, arrive at a point, first go the longest distance can get to the next point the minimum hop number.
First with the depth of the first traversal, so no accident, it must be timed out ~
Public intJumpint[] nums) {if(nums.length==1)return 0; List<integer>List=NewArraylist<integer> (); Findpath (0, Nums,0,List);List. Sort ((O1,o2)->{if(O1>O2)return 1;Else if(O1<O2)return-1;Else return 0; });return List. Get (0);} Public voidFindpath (intStartIndex,int[] Nums,intHavapassed,list<integer>List){intMaxdistance=nums[startindex]; for(intI=maxdistance;i>0; i--) {if((startindex+i) >= (nums.length-1)){List. Add (havapassed+1);return; } findpath (Startindex+i, Nums, havapassed+1,List); }}
Then think of the dynamic planning, but long time no use of dynamic planning, their own writing this kind of deformation, or will be timed out ~ ~ ~
PublicintJumpint[] nums) {if(Nums.length==1)return 0;int[] Jumps=newint[Nums.length]; Arrays.fill (jumps, integer.max_value); jumps[0]=0; for(intI=0; I<nums.length-1; i++) {if(I+nums[i]>=nums.length-1)returnJumps[i]; for(intj=1; j<=nums[i];j++) {if(I+j<nums.length) {Jumps[i+j]=integer.min(jumps[i]+1, Jumps[i+j]); } } }returnJumps[nums.length-1];}
Finally, referring to the practice of others, found that in fact, a little bit, from the past to traverse backward, you can reduce the number of traversal.
Public int Jump(int[] nums) {if(nums.length==1)return 0;int[] dp=New int[Nums.length]; Arrays.fill (DP, integer.max_value); dp[0]=0; for(intI=1; i<nums.length;i++) { for(intj=0; j<i;j++) {if(j+nums[j]>=i) {intTMP = dp[j]+1;if(TMP < dp[i]) {Dp[i] = tmp; Break; } } } }returndp[nums.length-1];}
There is also a greedy algorithm with less time complexity:
intJumpintA[]) {intN=a.length;intRET =0;//Current hop count intLast =0;//Previous hop up to the farthest distance intCurr =0;//Current hop up to the farthest distance for(inti =0; I < n; ++i) {//Cannot forward skip direct return if(I>curr) {System. out. println ("AAA");return-1; }if(i > Last) {last = Curr; ++ret; }//Record The farthest point that is currently reachedCurr = Integer.max (Curr, i+a[i]); }returnRet }
Jump Game II