/** * 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. For example: A = [2,3,1,1,4], return true. A = [3,2,1,0,4], return false. 動態規划題目,方法和找最大子串差不多,兩個題目共同的特點是 1.每遍歷一個元素都有可能影響最后的結果 2.都有局部解和最終解 3.都是通過解決局部解這個小問題而逐漸解決最終解的大問題 做這個題一開始的思路是:回溯法,從第一個數開始走,可能走的步數是[0,nums[i]],遍歷可能走的步數,設置一個 變量記錄這一步走到哪里了,下一次遞歸從變量處開始走,發現不能走了之后就返回,這樣時間復雜度取決於元素的大小 但是肯定比O(n)大,提交發現超時了 后來發現正確解法是動態規划。局部解就是i + nums[i],全局解就是最大的局部解。每次遍歷開始先判斷能不能走到這一步 也就是(glo >= i)?,不符合的話直接break,因為如果能到達最后,肯定前邊的都能到達。 最后比較glo和nums.length-1的大小。 注意遍歷的最終點事nums.length-2,數組的最后一個元素是不遍歷的。 */ public class Q55JumpGame { public static void main(String[] args) { int[] nums = new int[]{2,3,1,1,4}; System.out.println(canJump(nums)); } public static boolean canJump(int[] nums) { //判斷是不是能走到這里 if (nums.length == 1) return true int loc; int glo = 0; boolean res = false; for (int i = 0; i < nums.length-1; i++) { if (glo < i) break; //局部解和全局解 loc = i+nums[i]; glo = Math.max(glo,loc); } if (glo >= nums.length-1) res = true; return res; } }