码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Jump Game II

时间:2014-05-19 08:07:26      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   java   

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 没有被AC

bubuko.com,布布扣
public class Solution {
    public int jump(int[] A) {
        if(A.length==0)
            return 0;
        if(A[0]>=A.length)
            return 1;
        int[] step = new int[A.length];
        Boolean[] bol = new Boolean[A.length];
        
        step[0]=0;
        bol[0]=true;
        for(int i=1;i<A.length;i++){
            bol[i]=false;
            step[i]=0;
            for(int j=0;j<i;j++){
                if(bol[j]&&(A[j]+j)>=i){
                    bol[i]=true;
                    if((A[j]+j)>=A.length-1)
                        return step[j]+1;
                    int temp = step[j]+1;
                    if(step[i]==0){
                        step[i]=temp;
                    }else{
                        
                        if(step[i]>temp)
                            step[i]=temp;
                    }
                }
            }
        }
        return step[A.length-1];
        
    }
}
bubuko.com,布布扣

 

线性时间AC、

bubuko.com,布布扣
public class Solution {
    public int jump(int[] A) {
        if(A.length==0)
            return 0;
        if(A.length==1){
            return 0;
        }
            
        int[] step = new int[A.length];
        step[0]=0;
        int cur =0;
        Arrays.fill(step, 0);
        for(int i=0;i<A.length;i++){           
            int temp = i+A[i];
            if(temp>=A.length-1){
                return step[i]+1;
            }
            for(int j=cur+1;j<=temp;j++){
                step[j]=step[i]+1;
            }
            if(temp>=cur)
                cur=temp;
        }
        return step[A.length-1];
    }
}
bubuko.com,布布扣

 

【LeetCode】Jump Game II,布布扣,bubuko.com

【LeetCode】Jump Game II

标签:style   blog   class   code   c   java   

原文地址:http://www.cnblogs.com/yixianyixian/p/3732352.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!