DP动态规划专题八 :LeetCode 55. Jump Game

LeetCode 55. 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.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:

Input: [3,2,1,0,4]
Output: false

Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.

    public boolean canJump(int[] nums) {
        boolean[] dp = new boolean[nums.length];
        dp[0] = true;
        for (int i = 0; i < nums.length-1; i++) {
            if (dp[i]) {
                for (int p = nums[i]; p >= 1; p--) {
                    int index = p + i;
                    if (index < nums.length) dp[index] = true;
                    else return true;
                }
            }
        }
        return dp[dp.length -1];
    }

版本二:为了优化时间,我们可以先尝试走最大步数,如果不行,在回溯走小的步数,因此需要用recursion,另外用dp来标注不可以走到最后的点,如果再遇到这个点,就可以直接返回false.

    public boolean canJump(int[] nums) {
        boolean[] dp = new boolean[nums.length];
        return help(nums, 0, dp);
    }
    private boolean help(int[] nums, int i,  boolean[] dp) {
        if (i >= nums.length - 1) return true;
        if (dp[i]) return false;
        for (int j = nums[i]; j > 0; j--) {
            int pos = i + j;
            if (help(nums, pos, dp)) return true;
        }
        dp[i] = true;
        return false;
    }

猜你喜欢

转载自blog.csdn.net/katrina95/article/details/85395588
今日推荐