Jump Game

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.

Notes: Coordinate DP, from bottom to top method

  1. State: f[i] represents whether i could reach destination
  2. function: f[i] = OR(f[j]) j from i+1 to i+A[i] or A.length-1
  3. initialize: f[n-1] = true
  4. answer: f[0]
    public boolean canJump(int[] A) {
        if (A == null || A.length == 0) {
            return false;
        }

        // state
        boolean[] f = new boolean[A.length];

        // initialize
        f[A.length-1] = true;

        // function
        for (int i = A.length-2; i >= 0; --i) {
            if (A[i] > 0) {
                for (int j = i+1; j <= i+A[i] && j < A.length; j++) {
                    if (f[j]) {
                        f[i] = true;
                        break;
                    }
                }
            }
        }

        // answer
        return f[0];
    }

results matching ""

    No results matching ""