I. 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 ArrayA = [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.)
Two. Topic analysis
The main idea of the problem is that given an array, each element represents the distance that can be jumped from that position, asking at least how many times to jump from the first position to the last position.
Unlike jump game, the jump game asks if the array jumps to the last grid, which requires the number of hops to be calculated. The solution is still greedy, just set an array to record the path of the jump.
Three. Sample code
Class Solution { Public:int Jump(intA[],intN) {intresult =0;//Current number of hops intLast =0;//The maximum distance the previous hop can reach intCurr =0;//The maximum distance the current hop can reach for(inti =0; I < n; ++i) {//Cannot forward skip direct return if(i > Curr)return-1;//need to make the next jump, update last and the currently executed hop count result if(i > Last) {last = Curr; ++result; }//Update the furthest distance currently available for jumpingCurr = Max (Curr, I+a[i]); }returnResult }};
Four. Summary
Similar problem-solving ideas and BFS, the latter can be verified verification.
Leetcode notes: Jump Game II