[leetcode]55.JumpGame动态规划题目:跳数游戏

/**
 * 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.
 动态规划题目,方法和找最大子串差不多,两个题目共同的特点是
 1.每遍历一个元素都有可能影响最后的结果
 2.都有局部解和最终解
 3.都是通过解决局部解这个小问题而逐渐解决最终解的大问题
 做这个题一开始的思路是:回溯法,从第一个数开始走,可能走的步数是[0,nums[i]],遍历可能走的步数,设置一个
 变量记录这一步走到哪里了,下一次递归从变量处开始走,发现不能走了之后就返回,这样时间复杂度取决于元素的大小
 但是肯定比O(n)大,提交发现超时了
 后来发现正确解法是动态规划。局部解就是i + nums[i],全局解就是最大的局部解。每次遍历开始先判断能不能走到这一步
 也就是(glo >= i)?,不符合的话直接break,因为如果能到达最后,肯定前边的都能到达。
 最后比较glo和nums.length-1的大小。
 注意遍历的最终点事nums.length-2,数组的最后一个元素是不遍历的。
 */
public class Q55JumpGame {
    public static void main(String[] args) {
        int[] nums = new int[]{2,3,1,1,4};
        System.out.println(canJump(nums));
    }
    public static boolean canJump(int[] nums) {
        //判断是不是能走到这里
        if (nums.length == 1)
            return true
        int loc;
        int glo = 0;
        boolean res = false;
        for (int i = 0; i < nums.length-1; i++) {
            if (glo < i)
                break;
            //局部解和全局解
            loc = i+nums[i];
            glo = Math.max(glo,loc);
        }
        if (glo >= nums.length-1)
            res = true;
        return res;
    }
}

 

posted @ 2017-07-05 16:39  stAr_1  阅读(2126)  评论(0编辑  收藏  举报