55.Jump Game

来自WHY42
Riguz留言 | 贡献2023年10月31日 (二) 00:11的版本 →‎1D DP 2

Description

#55 Jump Game Medium
Dynamic Programming Top 150
You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise.

Example 1:

Input: nums = [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: nums = [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.

Solution

1D DP

Runtime 418ms
Memory 43.4MB
class Solution {
    public boolean canJump(int[] nums) {
        /*
            [2,3,1,1,4]
             1 1 2 2 2
         */
        int []dp = new int[nums.length];
        dp[0] = 1;
        for(int i = 0; i < nums.length; i++) {
            for(int j = 1; j <= nums[i]; j++){
                if(i+j >= dp.length) break;
                dp[i+j]++;
            }
                
        }
        for(int i = 0; i < dp.length; i++) {
            if(dp[i] == 0) return false;
        }
            
        return true;
    }
}

1D DP 2

Runtime 76ms
Memory 43.85MB
class Solution {
    public boolean canJump(int[] nums) {
        boolean []dp = new boolean[nums.length];
        dp[0] = true;
        for(int i = 0; i <nums.length; i++) {
            if(!dp[i]) return false;
            for(int j = 1; j <= nums[i]; j++) {
                int next = i + j;
                if(next >= dp.length) break;
                if(next == nums.length -1) return true; // reach end already
                dp[next] = true;
            }
        }
        return dp[nums.length-1];
    }
}

Greedy

Runtime 2ms
Memory 44.02MB
class Solution {
    public boolean canJump(int[] nums) {
        int max = 0;
        for(int i = 0; i < nums.length; i++) {
            if(i > max) return false;
            max = Math.max(max, i + nums[i]);
        }
        return true;
    }
}