# LeetCode 笔记系列13 Jump Game II [去掉不必要的计算]

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  public static int jump(int[] A) {
2             // Start typing your Java solution below
3             // DO NOT write main() function
4          if(A.length < 2) return 0;
5          int[] dist = new int[A.length];
6          int[] to = new int[A.length];
7          for(int i = 0; i < A.length; i++){
8              dist[i] = INFINITE;
9          }
10          dist[A.length - 1] = 0;
11          for(int i = A.length - 2; i >= 0; i--){
12              int minDist = INFINITE;
13              for(int j = 1; j <= A[i] && i + j < A.length; j++){
14                  int nextIdx = i + j;
15                  if(nextIdx < A.length){
16                      int candidate = dist[nextIdx] + 1;
17                      if(candidate < minDist){
18                          minDist = candidate;
19                          to[i] = nextIdx;
20                      }
21                  }
22              }
23              dist[i] = minDist;
24          }
25          return dist[0];
26      }
View Code

NB闪闪的，就不折叠鸟。

/*
* We use "last" to keep track of the maximum distance that has been reached
* by using the minimum steps "ret", whereas "curr" is the maximum distance
* that can be reached by using "ret+1" steps. Thus,
* curr = max(i+A[i]) where 0 <= i <= last.
*/
class Solution {
public:
int jump(int A[], int n) {
int ret = 0;
int last = 0;
int curr = 0;
for (int i = 0; i < n; ++i) {
if (i > last) {
last = curr;
++ret;
}
curr = max(curr, i+A[i]);
}

return ret;
}
};

O(n)的。。。。#我和我的小伙伴们都惊呆了#。

i继续前进，接下来发现超过当前势力范围，更新last和步数。cur已然最大了。

posted on 2013-07-10 23:13  lichen782  阅读(15997)  评论(3编辑  收藏  举报