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 steps to the last 3
index.)
The topic is jumping problem, using dynamic programming solution, record the furthest distance and number of steps at a time. Time: 16ms. The code is as follows:
classSolution { Public: intJump (vector<int>&nums) {size_t n=nums.size (); if(n = =0|| n = =1) return 0; intMaxstep = nums[0], step =1; if(Maxstep >= N-1) return 1; for(inti =1; I < n; i++){ if(Maxstep = =0) return-1; Maxstep--; if(Maxstep <Nums[i]) {Maxstep=Nums[i]; Step++; } if(Maxstep + i >= N-1) returnstep; } return-1; }};
[Leetcode] #45 jump Game II