Given an array of non-negative integers, you are initially positioned at the first index of the array.java
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.code
Example 2:递归
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.索引
给定一个非负整数数组,你最初位于数组的第一个位置。element
数组中的每一个元素表明你在该位置能够跳跃的最大长度。it
判断你是否可以到达最后一个位置。io
示例 1:
输入: [2,3,1,1,4]
输出: true
解释: 咱们能够先跳 1 步,从位置 0 到达 位置 1, 而后再从位置 1 跳 3 步到达最后一个位置。
示例 2:
输入: [3,2,1,0,4]
输出: false
解释: 不管怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 因此你永远不可能到达最后一个位置。
方法一:回溯法
由于会有多个递归函数,因此数组较长时,会出现栈溢出,不推荐此方法
方法二:动态规划
建立一个新数组status,记录原数组每一个元素的状态,能到达的为1,不能到达的为0,或者true,false。
class Solution { public boolean canJump(int[] nums) { int [] status = new int[nums.length]; status[0]=1; for(int i=0;i<nums.length;i++){ if(status[i]==1){ int step = nums[i]; if(i+step>=nums.length-1){ status[nums.length-1]=1; break; } for( j=1;j<=step;j++){ status[i+j]=1; } } } return status[nums.length-1]==1?true:false; } }
方法三:贪心算法
思路:尽量到达最远位置(贪心)。若是能到达某个位置,那必定能到达它前面的全部位置
方法:初始化最远位置为arr[0],而后遍历数组,判断当前位置可否到达(便是否在最远位置的范围内),若是在,则比较当前位置+跳数>最远位置,是就更新最远位置。若是当前位置不能达到,则退出
具体措施:遍历数组,每次都求一次当前位置所能到达的最远位置,并更新所能达到的最远位置k。遍历数组的一个新元素,和上一次的最远位置k进行比较,查看是否超出所能到达的最远位置,若超出,则返回flase,未超出,则对最远进行更新
class Solution { public boolean canJump(int[] nums) { int k = nums[0]; for(int i=0;i<nums.length;i++){ if(i>k){ return false; } if(nums[i]+i>k){ k=Math.max(k, nums[i]+i); if(k>=nums.length-1){ return true; } } } return true; } }