Tuesday, July 22, 2014

Jump Game I && II

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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

DP加贪心
public class Solution {
    //Time: O(n^2)  Space: O(n)
    public boolean canJump(int[] A) {
        if (A == null || A.length <= 1) {
            return true;
        }
        
        boolean[] map = new boolean[A.length];
        map[0] = true;
        for (int i = 1; i < A.length; i++) {
            for (int j = 0; j < i; j++) {
                if (map[j] && A[j] + j >= i) {
                    map[i] = true;
                    break;
                }
            }
        }
        return map[A.length - 1];
    }
}

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 is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

DP加贪心,这道题不需要考虑跳不到终点的情况。
public class Solution {
    //Time: O(n^2)  Space: O(n)
    public int jump(int[] A) {
        if (A == null || A.length <= 1) {
            return 0;
        }
        
        int[] map = new int[A.length];
        for (int i = 1; i < A.length; i++) {
            for (int j = 0; j < i; j++) {
                if (j + A[j] >= i) {
                    map[i] = map[j] + 1;
                    break;
                }
            }
        }
        return map[A.length - 1]; 
    }
}

No comments:

Post a Comment