【LeetCode】Jump Game II
2014-05-26 09:23
357 查看
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 =
The minimum number of jumps to reach the last index is
这道题目跟第一道题目有区别,如果用DP动态规划来解决的话,会出现超时的问题。。也有可能是自己用的不好,后面发现一种线性遍历获得最小步骤的方法
DP 没有被AC
线性时间AC、
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
1step from index 0 to 1, then
3steps to the last index.)
这道题目跟第一道题目有区别,如果用DP动态规划来解决的话,会出现超时的问题。。也有可能是自己用的不好,后面发现一种线性遍历获得最小步骤的方法
DP 没有被AC
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]; } }
线性时间AC、
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]; } }
相关文章推荐
- Leetcode_jump-game-ii(c++ and python version)
- Leetcode Jump Game II 解题报告
- Leetcode 45 Jump Game II
- [LeetCode] Jump Game II
- LeetCode-Jump Game II
- LeetCode第45之 Jump Game II
- leetcode - Jump Game II
- LeetCode | Jump Game II
- LeetCode_Jump Game II
- leetcode:Jump Game II
- leetcode[45]Jump Game II
- leetcode-Jump game II
- leetcode:Jump Game II 【Java】
- Leetcode NO.45 Jump Game II
- [leetcode 45] Jump Game II
- 【Leetcode】Jump Game II (DP)
- [leetcode-45]Jump Game II(java)
- LeetCode——Jump Game II
- leetcode_question_45 Jump Game II
- leetcode习题解答:45. Jump Game II