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.
Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
简单讲就是数组的每一位数字代表当前可以向前蹦跶的长度,求能不能从头走到尾
使用了递归,求能不能到最后一个数字,等价于求前面存不存在一个可以到最后一位的数字,又等于求前面存不存在一个可以到这个可以到最后一位的数字的数字……这样是不是有点绕(@_@;)
class Solution {
public boolean canJump(int[] nums) {
if(nums.length <= 1)
return true;
if (nums[0] == 0)
return false;
return canJump(nums, nums.length-1);
}
private boolean canJump(int[] nums, int end){
if (end == 0)
return true;
for (int i = end-1; i >= 0; i--){
if (i + nums[i] >= end)
return canJump(nums, i);
}
return false;
}
}