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, map[j] = Math.min(map[j], map[i] + 1)

 1 public class Solution {
 2     public int jump(int[] A) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(A == null || A.length == 0) return -1;
 5         int len = A.length;
 6         int[] map = new int[len];
 7         for(int i = 0; i < len; i ++){
 8             for(int j = i + 1; j - i <= A[i] && j < A.length; j ++){
 9                 if(i == 0){
10                     map[j] = 1;
11                 }else{
12                     map[j] = Math.min(map[j], map[i] + 1);
13                 }
14             }
15         }
16         return map[len - 1];
17     }
18 }

过不了大集合测试。

只能采用greedy做,依旧贪心去推,贪心的规则就是在能够到达的范围之内,选择一个能够到达最远距离的点,更新步数,和更新最远到达的范围。

 1 public class Solution {
 2     public int jump(int[] A) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         if(A == null){
 6             return 0;
 7         }
 8         int len = A.length;
 9         if(len == 0 || len == 1){
10             return 0;
11         }
12         
13         int cur = 0;
14         int next = 0;
15         int ret = 0;
16         
17         for(int i = 0; i < len; i++){
18             if(i > cur){
19                 cur = next;
20                 ret++;
21             }
22             next = Math.max(next, i + A[i]);
23         }
24         return ret;
25     }
26 }

第三遍: 

采用greedy来做。

 1 public class Solution {
 2     public int jump(int[] A) {
 3         if(A == null || A.length < 2) return 0;
 4         int[] step = new int[A.length];
 5         step[1] = A[0];
 6         int max = 0;
 7         int cur = 1;
 8         while(step[cur] < A.length - 1){
 9             for(int i = step[cur - 1]; i <= step[cur]; i ++){
10                 max = Math.max(max, i + A[i]);
11             }
12             cur ++;
13             step[cur] = max;
14         }
15         return cur;
16     }
17 }
原文地址:https://www.cnblogs.com/reynold-lei/p/3343888.html