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.)
如题,求到达末位最少的跳的次数。
1 class Solution { 2 private: 3 int dp[100000]; 4 public: 5 int jump(vector<int>& nums) { 6 int maxPos = 0; 7 dp[0] = 0; 8 int pos = 0; 9 int sz = nums.size(); 10 for(int i = 0; i <= maxPos; ++i){ 11 pos = i + nums[i]; 12 if(pos >= sz) 13 pos = sz - 1; 14 if(pos > maxPos){ 15 for(int j = maxPos + 1; j <= pos; ++j) 16 dp[j] = dp[i] + 1; 17 maxPos = pos; 18 } 19 20 if(maxPos == sz - 1) 21 return dp[sz - 1]; 22 } 23 24 } 25 };