Jump Game II -- LeetCode

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

                原题链接:  http://oj.leetcode.com/problems/jump-game-ii/  
这道题是 Jump Game 的扩展,区别是这道题不仅要看能不能到达终点,而且要求到达终点的最少步数。其实思路和 Jump Game 还是类似的,只是原来的全局最优现在要分成step步最优和step-1步最优(假设当前步数是step)。当走到超过step-1步最远的位置时,说明step-1不能到达当前一步,我们就可以更新步数,将step+1。时间复杂度仍然是O(n),空间复杂度也是O(1)。代码如下:
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;}
动态规划是面试中特别是onsite中非常重要的类型,一般面试中模型不会过于复杂,所以大家可以熟悉一下比较经典的几个题,比如 Jump Game Maximum Subarray 等。
           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43418664/article/details/84076654