Jump game I
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.
[code]
public class Solution {
public boolean canJump(int[] A) {
if(A==null || A.length<2)return true;
boolean dp[]=new boolean [A.length];
Arrays.fill(dp, false);
dp[0]=true;
for(int i=1;i<A.length;i++)
{
int j=i-1;
while(j>=0)
{
if(dp[j]==true && A[j]>=i-j)
{
dp[i]=true;break;
}
j--;
}
if(j<0)dp[i]=false;
}
return dp[dp.length-1];
}
}
Jump game II
reach the last index in the minimum number of jumps.
[code]
public class Solution {
public int jump(int[] A) {
if(A==null || A.length<2)return 0;
int start=0, end=0, jumps=0;
while(start<=end && end<A.length-1)
{
int max=end;
for(int i=start;i<=end;i++)
{
max=Math.max(max, i+A[i]);
}
start=end+1;
end=max;
jumps++;
}
return jumps;
}
}
[Thoughts]
做 I 的时候没有想到用贪心, 就用dp做了。
贪心的思想是每次找到能reach的最远距离,code也简洁很多