55.Jump Game:修订间差异

来自WHY42
Riguz留言 | 贡献
Created page with "=Description= {{LeetCode |id=jump-game |no=55 |difficulty=Medium |category=Dynamic Programming |collection=Top 150 |title=Triangle |summary=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: <syntaxhighlight lang="bash"> Input: nums = [2,3,1,1,4] Output: true </synta..."
 
Riguz留言 | 贡献
第28行: 第28行:
=Solution=
=Solution=
==1D DP==
==1D DP==
{{Submission|runtime=418ms|memory=43.4MB|rp=7.2|mp=97.69}}
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
class Solution {
class Solution {

2023年10月10日 (二) 23:05的版本

Description

#55 Triangle 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;
    }
}