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.
ไปฃ็
Approach #1: Dynamic Programming
publicclassSolution {publicbooleancanJump(int[] A) {boolean[] f =newboolean[A.length]; f[0] =true;for (int i =1; i <A.length; i++) {for (int j =0; j < i; j++) {if (f[j] && j +A[j] >= i) { f[i] =true;break; } } }return f[A.length-1]; }}
Approach #2: Greedy
publicclassSolution {publicbooleancanJump(int[] A) {if (A ==null||A.length==0) {returnfalse; }int farthest =A[0];for (int i =1; i <A.length; i++) {if (i <= farthest &&A[i] + i >= farthest) { farthest =A[i] + i; } }return farthest >=A.length-1; }}
classSolution {publicbooleancanJump(int[] nums) {int n =nums.length;int maxPos = nums[0];for (int i =1; i < n; i++) {if (maxPos < i) {returnfalse; } maxPos =Math.max(maxPos, nums[i] + i); }returntrue; }}