Solution by me:
public class Solution {
public boolean canJump(int[] A) {
if(A.length == 0) return false;
int[] B = new int[A.length];
Arrays.fill(B,-1);
return canJump(A,0,B);
}
public boolean canJump(int[] A, int crntIdx, int[] B){
if(crntIdx >= A.length - 1){
B[A.length - 1] = 1;
return true;
}
if(B[crntIdx] != -1){
return (B[crntIdx] == 0 ? false:true);
}
if(A[crntIdx] == 0) {
B[crntIdx] = 0;
return false;
}
int i = A[crntIdx];
while(i > 0 && !canJump(A,crntIdx+i,B)){
i--;
}
if((crntIdx+i) < (A.length - 1)) B[crntIdx+i] = (i == 0 ? 0: 1);
// else B[A.length - 1] = (i == 0 ? false: true);
else return true;
return (B[crntIdx+i] == 0 ? false:true);
}
}
Solution by Code Ganker .In his post, he considers the "local maximum and global maximum reach" the elements in array A could get to, and if the global reach is larger than last index, then it must be TRUE.
Thanks to Code Ganker for his brilliant idea.
public boolean canJump(int[] A) {
if(A==null || A.length==0)
return false;
int reach = 0;
for(int i=0;i<=reach&&i<A.length;i++)
{
reach = Math.max(A[i]+i,reach);
}
if(reach<A.length-1)
return false;
return true;
}
No comments:
Post a Comment