Leetcode45. Jump Game II

自己先写了一个backtracking的方法,但是不好使:

class Solution {
    public int jump(int[] nums) {
        if(nums==null||nums.length==0) return -1;
        if(nums.length==1) return 0;
        return helper(nums,0,0);
    }
    private int helper(int[] nums,int cur,int count){
        if(cur+nums[cur]>=nums.length-1) return count+1;
        if(nums[cur]>0){
            int min_count=helper(nums,cur+1,count+1);
            for(int i=2;i<=nums[cur];i++){
                min_count = Math.min(min_count,helper(nums,cur+i,count+1));
            }
            return min_count;
        }else{
            return Integer.MAX_VALUE;
        }
    }
}
Last executed input
[5,6,4,4,6,9,4,4,7,4,4,8,2,6,8,1,5,9,6,5,2,7,9,7,9,6,9,4,1,6,8,8,4,4,2,0,3,8,5]
超时了。
想想怎么改进。
看了discuss,原来dfs还可以这么写,不过也因为这个题的特殊性吧。这种写法也要掌握。
class Solution {
    public int jump(int[] nums) {
        if(nums.length<=1) return 0;
        int level=0,i=0,currentMax=0,nextMax=0;
        while(i<=currentMax) {//why not i<=nums.length-1? Because there maybe many zeroes so that we can never reach the last position
            level++;
            for(;i<=currentMax;i++){
                if(i+nums[i]>=nums.length-1) return level;
                nextMax=Math.max(nextMax,nums[i]+i);
            }
            currentMax=nextMax;
        }
        return -1;
    }
}

5ms,90.13%。可以了。

posted @ 2019-01-01 11:46  大胖子球花  阅读(104)  评论(0)    收藏  举报