您的位置:首页 > 其它

[leetcode解题记录]Jump Game和Jump Game II

2015-01-12 20:49 429 查看
Jump Game

  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
.

  从题目的意思是给一个非负的整数数组,你的初始位置在第一个元素,每个元素的值代表该位置可以跳跃的最大距离。用算法判断你是否可以到达最后一个元素。

  提示的标签是数组和贪心(greedy),但是这个应该是动态规划解,因为贪心算法需要保证必须有解,这里尚需判断,并不能保证。

  我们用maxposition维护一个从开始位置能到达的最远位置,然后判断在当前位置是否能够到底最后一个位置和当前位置是否可达,如果两个条件都满足,那么返回true,如果当前位置是0,并且最远位置不能超过当前位置,那么只能返回false 了,更新最远位置。java代码如下:

public boolean canJump(int[] A){
if(A.length <= 1)
return true;
if(A[0] >= (A.length-1))
return true;
int maxposition = A[0];
if(maxposition == 0)
return false;
for(int i = 1; i < A.length - 1; i++){
if(maxposition >= i && (i + A[i]) >= A.length -1)
return true;
if(maxposition <= i && A[i] == 0)
return false;
if(maxposition < (i + A[i]))
maxposition = i + A[i];
}
return false;
}


或者可以这样写

public boolean canJump(int[] A){
int maxposition = 0;
for(int start = 0; start <= maxposition && start < A.length; start ++){
if((A[start] + start) > maxposition)
maxposition = (A[start] + start);
if(maxposition >= (A.length - 1))return true;
}
return false;
}


Jump Game II

  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.

  Your goal is to reach the last index in the minimum number of jumps.

  For example:
  Given array A =
[2,3,1,1,4]


  The minimum number of jumps to reach the last index is
2
. (Jump
1
step from index 0 to 1, then
3
steps to the last index.)

  题目的意思是求到达最后元素的最小跳跃步数。用贪心算法,解法如下(java),可以通过。但是如果没有解呢?或者贪心法找不到解呢?

public int jump(int[] A){
int maxx=0,temp=0,count=0;
for(int i = 0; i < A.length;){
if(temp >= (A.length-1)) break;
while(i <= temp)
{
maxx = maxx>(i + A[i])?maxx:(i + A[i]);
i++;
}
count++;
temp = maxx;
}
return count;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: