One Day Together Leetcode series (i) Title
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.
(ii) Problem solving
1, the first thought of the practice is for the serial number I, Judge I+nums[i] can reach the end, if you can return directly, if not less than nums[i] The number of recursion, to get the smallest min value. This is a direct timeout, tle!.
classSolution { Public:intMinintJump vector<int>& nums) {min = Nums.size (); Jumpdfs (Nums,0,0);returnMin }voidJumpdfs ( vector<int>& Nums,intIDX,intCount) {intLen = Nums.size ();if(IDX >= len-1) {min = count;return; }if(Idx<len && idx + nums[idx] >= len-1) {min = min> (count+1)? (count+1): min;return; }Else{ for(inti =1; Idx<len && i<= Nums[idx]; i++) {Jumpdfs (nums,idx+i,count+1); } } }};
2, and then see the hint mentioned greedy algorithm, so Lenovo to yesterday to do the wildcard, you can record the last hop can reach the farthest position, and the current jump can reach the farthest position, each cycle will update the two values, until the last hop can reach the end of the exit.
/* Idea: The greedy algorithm is supposed to make the current optimal solution every time, so for the subject, record the current farthest position each time, and the farthest position of the previous hop. */classSolution { Public:intJump vector<int>& Nums) {intRET =0;intLast =0;intCur =0; for(inti =0; I < nums.size (); i++) {if(Last>=nums.size ()-1) Break;if(I>last)//If the current position has jumped from the farthest position of the previous hop{last = cur;//Update the farthest position of the previous hop equals the farthest position of the current hop++ret;//Hop count plus 1} cur = max (cur, i+nums[i]);//Update the farthest position of the current jump}returnRet }};
"One Day together Leetcode" #45. Jump Game II