package easy.greedy;
import org.junit.Test;
public class Jump {
int minstep =100000;
public int jump(int[] A) {
int step = 0 ;
if(A.length==1)return 0;
jumping(A, step, 0, 0);
return minstep;
}
public void jumping(int[] A,int step,int location,int length) {
if(location>=A.length-1) {
if(minstep>step)minstep=step;
return;
}
//从这个位置跳
if(length>=location) {
if(length<=(location+A[location])) {
length = location+A[location];
}
//可以走
int chance = A[location];
while(chance>0) {
location = location + chance;
step++;//从location跳出去
jumping(A, step, location, length);
step--;
location = location - chance;
chance--;
}
}
}
@Test
public void test() {
int[] A= {2,3,1,1,4,5,8,1,1};
System.out.println(jump(A));
}
}
这个算法复杂度太大,必须简化
这种方法是简化的方法:逻辑很清晰,即遍历数组,如果超出上一步能达到的最大值,就跳,并把当前所能达到的最大值赋给上一步能达到的最大值,代表跳了一步。如果最后上一步能达到数组最后一位,返回结果,否则,返回-1
public class Solution {
public int jump(int[] A) {
int step = 0;
if (A.length == 1)
return 0;
int curFarest = 0;//当前能跳的最远的地方
int lastFarest = 0;//上一步能跳的最远的地方
for (int i = 0; i < A.length; i++) {
if(i>lastFarest) {
step++;
lastFarest = curFarest;
}
curFarest = i+A[i]>curFarest?i+A[i]:curFarest;
}
if(lastFarest>=A.length-1) {
return step;
}
return -1;
}
}