Problem description:
Level: medium
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.
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.)
Solution:
Consider DP
State: f[i] means the minimum steps I can jump to position i
function: f[I] = minimum(f(j), j < i & j+a[j] >= i, j can jum to i) — mean if there is one j can jump to i
initialize: f[0] = 0
Answer: f[n-1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public int jump(int[] A) { if(A.length == 0) return 0; // initialize int f[] = new int[A.length]; for(int i = 0; i < A.length; i++) { f[i] = Integer.MAX_VALUE; } f[0] = 0; for(int i = 1; i < A.length; i++) { for(int j = 0; j < i; j++) { if(f[j] < Integer.MAX_VALUE && j + A[j] >= i) { f[i] = Math.min(f[i], f[j] + 1); } } } return f[A.length-1]; } |