您的位置:首页 > 其它

[LeetCode]Jump Game II(贪心&&DP!!!!!)

2015-07-18 13:27 363 查看
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.)

题目的意思是求出到达终点的最小步数,看似可以用Dp来做,就会发现dp实际上会TLE。使用贪心来处理

原来的全局最优现在要分成step步最优和step-1步最优(假设当前步数是step)。当走到超过step-1步最远的位置时,说明step-1不能到达当前一步,我们就可以更新步数,将step+1。时间复杂度仍然是O(n),空间复杂度也是O(1)。

这种处理方法可以看成是对step的dp处理

public int jump(int[] A) {
if(A==null || A.length==0)
return 0;
int lastReach = 0;
int reach = 0;
int step = 0;
for(int i=0;i<=reach&&i<A.length;i++)
{
if(i>lastReach)
{
step++;
lastReach = reach;
}
reach = Math.max(reach,A[i]+i);
}
if(reach<A.length-1)
return 0;
return step;
}


类似的题目有Container With Most Water

还有另外一种比较好理解的思路是我们每次都维护一个区间,这个区间表示的是第i步能到达的最大范围,

递推的方法为:每次都遍历一遍当前区间内的所有元素,从一个元素出发的最远可达距离是index+array[index],那么下一个区间的左端点就是当前区间的右端点+1,下一个区间的右端点就是当前区间的max(index+array[index]),以此类推,直到区间包含了终点,统计当前步数即可。

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