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 is2
. (Jump1
Step from index 0 to 1, then3
Steps to the last index .)
The original idea was similar to the dynamic planning in the jump game. If you forget the question, you can do it with greed. The result times out. paste the Code:
1 public int jump(int[] A) { 2 if(A==null||A.length==0){ 3 return 0; 4 } 5 int step[] = new int[A.length]; 6 for (int i = A.length - 1; i >= 0; i--) { 7 if (i == A.length - 1) { 8 step[i] = 0; 9 } else {10 int min = Integer.MAX_VALUE;11 for (int j = i + 1; j <= i + A[i] && j < A.length; j++) {12 if(min>A[j]){13 min=A[j];14 }15 }16 step[i] = min + 1;17 }18 }19 return step[0];20 }
This can be done with greed, set SIJ to the number of steps from I to J, there is SIJ = min (sik + skj) (k from I + 1 to J-1 ). The last node on the route where k is the optimal solution. If f [I] is set, it indicates the position that can be reached from any position less than or equal to I. Then K is the minimum value that satisfies f [k] = J. Proof: If P <K makes f [p] = J, SIJ = min (SIP + 1, sik + 1) Because SIP <= Sik (proof later) = sip + 1. Therefore, p is the last node on the optimal route and conflicts with K as the last node. Therefore, this assumption is not true, therefore, k is the minimum value that satisfies f [k] = J. The following example shows that when P <K, SIP <= Sik. Set V to the last node on the SIJ optimal route. Therefore, SIP = SIV + 1. If the maximum value is K from the V node, Sik = SIV + 1, because the node before v cannot reach P, it cannot reach k either. If the slave v node cannot reach K, Sik> SIV + 1. We can see that sip <= Sik. Therefore, we can use the greedy method to solve this question. The greedy step is to find the farthest point that can be reached each time. If the farthest point is updated, add 1 to the step size. The following code is available:
1 public int jump(int[] A) { 2 int step = 0; 3 int last = 0; 4 int cur = 0; 5 for (int i = 0; i < A.length; ++i) { 6 if (i > last) { 7 last = cur; 8 ++step; 9 }10 cur = cur > i + A[i] ? cur : i + A[i];11 }12 return step;13 }
For the first question of Jump game, see jump game.