JunyiCode
3/24/2020 - 11:57 PM

45. Jump Game II

hard,多巩固

/*
1. Initiate the maximum position that one could reach starting from the current index i or before: max_pos = nums[0].
2. Initiate the maximum position reachable during the current jump: max_steps = nums[0].
3. Initiate number of steps: at least one, if array has more than 1 cell.

*/

class Solution {
    public int jump(int[] nums) {
        int sofar = 0, next = 0;
        int res = 0;
        
        for(int i = 0 ; i < nums.length; i++){            
            if(i > sofar){
                res++;
                sofar = next;
            }
            next = Math.max(next, nums[i] + i);
        }
        
        return res;
    }
}
/*
Define state(i) as the minimum jumps to reach i
state(i) = min(1 + state(j)) for each j that can jump to i.
The goal state is state(nums.length - 1).
*/

class Solution {
    public int jump(int[] nums) {
       int[] state = new int[nums.length];
       Arrays.fill(state, Integer.MAX_VALUE);
       state[0] = 0;
        
       for(int i = 1; i < nums.length; i++) {
            for(int j = 0; j < i; i++) {
                if(nums[j] + j > i) {
                    state[i] = Math.min(state[i], state[j] + 1);
                }
            }
       }
        
        return state[nums.length - 1];
    }
}
/*
time limit
*/

class Solution {
    int res = Integer.MAX_VALUE;
    
    public int jump(int[] nums) {
        backtrack(nums, 0, 0);
        return res;
    }
    
    public void backtrack(int[] nums, int count, int position) {
        if(position == nums.length - 1) {
            res = Math.min(res, count);
            return;
        }
        
        int furthestJump = Math.min(nums.length - 1, position + nums[position]);
        
        for(int i = position + 1; i <= furthestJump; i++) {
            count++;
            backtrack(nums, count, i);
            count--;
        }   
        
        return;
    }
}