Leetcode #45. Jump Game II 跳跃游戏2 解题报告

1 解题思想

今天从4点就在赶一个作业,赶死我了。。。被猪队友坑的节奏,赶在12点钱来更新。。更新完继续写作业,好累。还是到Hard的模式,还是简单点说,

这道题还是跳跃游戏,每一位置的取值代表能跳到的最远的位置。这道题不能暴力似乎也不能用原始的DP

简单说解决方法:
用了贪心的策略,reached和times表示跳了times次后,某一段区间内最小的步伐到达数量,而times的计算需要一个上下界,这个可以看我代码的注释,写作业去了

2 原题

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.)

3 AC解

public class Solution {
    /**
     * http://www.cnblogs.com/ganganloveu/p/3761715.html
     * 我是看了上面那个解析的
     * 
     * times就是跳了多少次
     * reached就是当前跳了times次时能到的最远范围
     * max是路过的位置之处再跳一次能到达的最远的位置
     * 
     * 总之就是用了贪心的策略,reached和times表示跳了times次后,某一段区间内最小的步伐到达数量
     * 
     * 而max则记录了路过的所有节点的,再跳一次能有多远,这个可以用来更新reached
     * 
     * */
    public int jump(int[] nums) {
        int times = 0;
        int reached = 0;
        int max = 0;
        for(int i=0;i< nums.length;i++){
            if(reached < i){
                times++;
                reached = max;
            }
            max = Math.max(max,i+nums[i]);
        }
        return times;
    }
}

你可能感兴趣的:(leetcode,游戏,跳跃,贪心,DP,leetcode-java)