[LintCode] 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.

 Notice

This problem have two method which is Greedy and Dynamic Programming.

The time complexity of Greedy method is O(n).

The time complexity of Dynamic Programming method is O(n^2).

We manually set the small data set to allow you pass the test in both ways. This is just to let you learn how to use this problem in dynamic programming ways. If you finish it in dynamic programming ways, you can try greedy method to make it accept again.

Example

A = [2,3,1,1,4], return true.

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


 

 思路一:

动态规划,dp[i]表示走到i点剩余的最大步数。所以dp[i]就是之前那个点的剩余最大步数和可以走的最大步数中较小的那个减1。但是需要注意的是,在循环的过程中,如果dp[i]的值有<0的情况,说明没有剩余步数,说明到不了最后。

public class Solution {
    /*
     * @param A: A list of integers
     * @return: A boolean
     */
    public boolean canJump(int[] A) {
        // write your code here
        if (A == null || A.length == 0) {
            return false;
        }
        
        //dp[i] 走到位置i上,剩余最大的步数
        int[] dp = new int[A.length];
        
        for (int i = 1; i < A.length; i++) {
            dp[i] = Math.max(dp[i - 1], A[i - 1]) - 1;
            if (dp[i] < 0) return false;
        }
        return dp[A.length - 1] >= 0;
    }
}

思路二:

用一个值来代表最远能走到的点。当现在的位置比这个值大,或者这个距离已将大于数组最后一位了,就可以停止循环。不然这个值就是从i这个位置上向后可以跳A[i]的值,即i+A[i], 同现在这个值的大小比较,取较远的那个(大)。

public boolean canJump(int[] A) {
        // write your code here
        if (A == null || A.length == 0) {
            return false;
        }
        
        int max = 0;
        for (int i = 0; i < A.length; i++) {
            if (i > max || max > A.length - 1) break;
            max = Math.max(i + A[i], max);
        }
        return max >= A.length - 1;
    }

 

 

你可能感兴趣的:([LintCode] Jump Game)