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

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值