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; } }