题目:
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.)
这题要求调到指定位置需要的最小步数,可以用递归,但是TLE了。
我们可以换一个角度来思考,如果我们知道指定步数能够达到的最远距离,那么只要逐步增加步数,当这个最远距离超过阈值时就返回结果就可以了。
那么接下来的问题就是如何求出指定步数n下能达到的最远距离,不妨设这里距离为f(n)
要在第n步到达f(n),那么n-1步所到达的位置X(n-1),它一定小于等于f(n-1),同理我们有X(n-2)<= f(n-2),因此只要我们在n-2时到达X(n-2),一定可以在第n时到达f(n),所以我们只需求出X(n-2)即可,即在X(n-3)一定的情况下,遍历找到使第n-1步达到最远距离的X(n-2),这样找出来的最远距离就是f(n-1)。
换个说法:已知X(0)=0,f(1)=A[1],找到X(1)使得第2步能到达最远,再以X(1)为基点,找到能使第3步到达最远的X(2),这样找到的X序列即为最优解,在求解的过程中还可以求出f(n)。
public class No44_JumpGameII {
public static void main(String[] args){
System.out.println(jump(new int[]{2,3,1,3,1,1,7}));
}
public static int jump(int[] A) {
if(A.length == 1) return 0;
int ret = 1;
int furthest = A[0];
int start = 0;
while(furthest < A.length-1){
int end = start + A[start];
for(int i=start+1;i<=end;i++){
if(i+A[i]>furthest){
furthest = i + A[i];
start = i;
}
}
ret++;
}
return ret;
}
}