# 45-跳跃游戏II

Description:

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.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.

Note:
You can assume that you can always reach the last index.

class Solution {
public int jump(int[] nums) {
int len = nums.length;
int[] dp = new int[len];
//对数组初始化为最大值
for(int i = 0;i < len;i++)  dp[i] = len;
dp[0] = 0;

for(int i = 1;i < len;i++){
for(int j = 0;j < i;j++){
//条件判断代表j下标可以跳跃到i并且可以使到达i的步数变少
if(j + nums[j] >= i && dp[j] < dp[i]){
dp[i] = Math.min(dp[i], dp[j] + 1);
break;
}
}
}

return dp[len - 1];
}
}

class Solution {
public int jump(int[] A) {
/*
step_count代表总步数
last_jump_max代表上一个最远界
current_jump代表正在被更新，下次使用的最远界
*/
int step_count = 0, last_jump_max = 0, current_jump_max = 0;

//迭代，更新current_jump,若到达上次最远界，jump增1，将last_jump_max置为current_jump_max
for(int i = 0; i < A.length - 1; i++) {
current_jump_max = Math.max(current_jump_max, i + A[i]);
if( i == last_jump_max ) {
step_count++;
last_jump_max = current_jump_max;
}
}

return step_count;
}
}