Jump Game II
Given an array of non-negative integers, you is initially positioned at the first index of the array.
Each element of the array represents your maximum jump length is 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 and then 3 steps to the last index.)
Solution 1:
Reference: http://blog.csdn.net/fightforyourdream/article/details/14517453
We can use greedy methods to solve this problem.
Think back and forth about the problem. Take des = len-1 reverse thinking. Think of the farthest distance that can reach it.
Example:
2 3 1) 1 4
i = 1
In the example above, index i = 2 is the furthest distance to reach 4. At this point, the index i = 1 to 4 is the best solution for the last step, because the other solution, if you jump to index = 2, 3 to 4 is the last step, then the second step is to reach index = 2, 3 can also reach index = 1, so jump to index = 1 steps will be the same. So the other best solution is to jump from index = 2.
The previous point, because of the distance limit, may only jump to index = 1, not to index = 2, 3. So the second-to-last step is set at index = 1 to get the most solution.
1 PackageAlgorithms.greedy;2 3 Public classJump {4 Public Static voidMain (string[] strs) {5 int[] A = {2, 3, 1, 1, 4};6 System.out.println (Jump (A));7 }8 9 Public Static intJumpint[] A) {Ten if(A = =NULL|| A.length = = 0) { One return0; A } - - intLen =a.length; the - intsum = 0; - - intDes = len-1; + while(des > 0) {//Destination Index - for(inti = 0; i < des; i++) {//Keep moving forward dest + if(A[i] + i >= des) {//description from I position can be 1 steps to reach the position of dest Asum++; atdes = i;//To update the dest location, the next step is to calculate how many steps can be transferred to the current I position - //Break ;//There's no need to keep looking, because the sooner I can find it , the better it is, the farther away the jump is. - //This line can be removed, des = i, does not meet for the conditions, will automatically break. -System.out.println ("Sum:" +sum); -System.out.println ("des:" +des); - } in } - } to + returnsum; - } the}
View Code
GITHUB:
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/greedy/Jump.java
Leetcode:jump Game II Problem Solving report