[leetcode]Jump Game II

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.)

算法思路:

[leetcode]Jump Game类似,不过数组不仅仅记录可达性,要记录最短路由跳数。思想一样。

例如[25000,24999,24998,24997,24996,24995,24994,24993......1]这个栗子,如果不记录最远可达(approach)的话,重复计算,势必超时

代码如下:

 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         for(int i = 1; i < a.length; i++){
 6             step[i] = a.length;
 7         }
 8         int approach = 0;
 9         for(int i = 0; i < a.length; i++){
10             int cover = i + a[i];
11             if(cover <= approach) continue;
12             for(int j = approach; j <= Math.min(cover,a.length - 1); j++){
13                 step[j] = Math.min(step[i] + 1,step[j]);
14             }
15             approach = i + a[i];
16         }
17         return step[a.length - 1];
18     }
19 }
原文地址:https://www.cnblogs.com/huntfor/p/3898462.html