leetcode -- Jump Game II
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.)
[解题思路]
1.DP: let F(i) denote the minimum number of jumps, then we have F(i) = min(F(j) ) + 1 where j = 0, … i – 1 && A[j] + j >=i, this is O(N^2) approach and will get TLE by the OJ
1 public int jump(int[] A) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 int len = A.length; 5 if(len <= 1){ 6 return 0; 7 } 8 int[] f = new int[len]; 9 for(int i = 0; i < len; i++){ 10 f[i] = Integer.MAX_VALUE; 11 } 12 f[0] = 0; 13 for(int i = 1; i < len; i++){ 14 for(int j = 0; j < i; j++){ 15 if(A[j] + j >= i){ 16 f[i] = Math.min(f[i], f[j] + 1); 17 } 18 } 19 } 20 return f[len - 1]; 21 }
2.Greedy
have bugs, the problem in the code: do not understand or realize when we need to do hops++!!!
That is to say: i did not find the way to solove this question
1 public int jump(int[] A) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 int len = A.length; 5 if(len <= 1){ 6 return 0; 7 } 8 9 int maxDis = A[0] + 0; 10 int hops = 0; 11 if(maxDis >= len - 1){ 12 return hops + 1; 13 } 14 int i = maxDis; 15 for(; i < len; i++){ 16 if(A[i] + i > maxDis){ 17 maxDis = A[i] + i; 18 hops += 1; 19 i = maxDis; 20 } 21 if(maxDis >= len - 1){ 22 break; 23 } 24 } 25 26 if(i == len - 1){ 27 return hops; 28 } else{ 29 return hops + 1; 30 } 31 }
updated 20130910
inspired by the discussion in leetcode and http://tech-wonderland.net/blog/leetcode-jump-game-ii.html
the keypoint of solving the problem by greedy approach is that we should keep the current maxium reachable distance, the next maxium reachable distance and also the steps needed to do it.
when the index exceed the current maxium reachable distance, then we need to update it by the next maxium reachable distance and increase the steps by steps ++,
because when the index exceed the current maxium reachable distance, it means that we are stuck in current maxium reachable distance, we need to jump to increase the next maxium distance.
1 public int jump(int[] A) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 if(A == null){ 5 return 0; 6 } 7 int len = A.length; 8 if(len == 0 || len == 1){ 9 return 0; 10 } 11 12 int cur = 0; 13 int next = 0; 14 int ret = 0; 15 16 for(int i = 0; i < len; i++){ 17 if(i > cur){ 18 cur = next; 19 ret++; 20 } 21 next = Math.max(next, i + A[i]); 22 } 23 return ret; 24 }