Thursday, February 5, 2015

LeetCode [45] Jump Game II

 45. Jump Game II

Hard

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:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.

Note:

You can assume that you can always reach the last index.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    int n;
    Set<Integer> visited = new HashSet<>();
    public boolean canReach(int[] arr, int start) {
        this.n = arr.length;
        visited.add(start);
        return dfs(arr, start);

    }

    boolean dfs(int[] arr, int node){
        if(arr[node]==0) return true;
        int left = node-arr[node], right = node+arr[node];
        if(left>=0 && !visited.contains(left)){
            visited.add(left);
            if(dfs(arr, left)) return true;
        }
        if(right<n && !visited.contains(right)){
            visited.add(right);
            if(dfs(arr, right)) return true;
        }
        return false;
    }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    public int jump(int[] nums) {
        int n = nums.length, curEnd = 0, reach = 0;
        int jumps = 0;
        for(int i=0; i<n; ++i){
            if(curEnd>=n-1) return jumps;
            if(reach<i+nums[i]){
                reach = i+nums[i];
            }
            if(i==curEnd){
                jumps++;
                curEnd = reach;
            }
        }
        return jumps;
    }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    public int jump(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        
        for(int i=0; i<n; ++i){
           // int left = Math.max(0, i-nums[i]);
            int right = Math.min(n-1, i+nums[i]);
            for(int j = i+1; j<=right; ++j){
                dp[j] = Math.min(dp[j], dp[i]+1);
            }
        }
        return dp[n-1];
    }
}

No comments:

Post a Comment