At first, I thought it was a DP solution, create a Boolean array to store the status which mark whether the person can get to the end from current posit Ion.
But with this methods, we would encounter the worst case, which are there ' re Hugh number of index and from which person Woul D finally jump to a trap, i.e., nums[target] = 0. The If we use DP, we need to look through all the previous Boolean value and the possibility (the index value Lar GER than the current index value). Thus, the runtime is likely O (n^3).
Greedy, we traverse the array from the len-1 to 0 which are same as DP, the only difference is so when we find a nums[i] = 0 Index, the boolean value of the index would is false, we then look through all the POS before this trap POS, use a loo p to get all the consecutive positions this would eventually jump to the trap and mark the corresponding status to be Fals E.
Code:
public class Solution {public boolean canjump (int[] nums) {int len = nums.length; if (len = = 0) return false; if (len = = 1) return true; boolean[] Posjump = new Boolean[len]; int i = len-1; Posjump[i] = true; int target = len-1; while (i>=1) {if (i-1+nums[i-1] >= i) {posjump[i-1] = true; i--; } else{Posjump[i-1] = false; int sink = i-1; i = i-1; while (I>=1 && (i-1) +nums[i-1] <= sink) {Posjump[--i] = false; } if (I >= 1) posjump[i-1] = true; i--; }} return posjump[0]; }/* Public boolean ToPos (int[] nums, int len, int index, boolean[] flag) {int steps = Nums[index]; if (index + steps >= len-1) {Flag[index] = true; return true; } if (Index < len-1 && steps = = 0) {Flag[index] = false; return false; }//int Num_step = new Int[steps]; for (int i = 1; I <= steps; i++) {Flag[index] = Flag[index] | | toPos (nums, Len, index+i, flag); if (Flag[index]) return Flag[index]; } return false; } */}
Jan 18-jump Game; Array; greedy;