LeetCode

[LeetCode] Medium - 55 Jump Game

NIMHO 2023. 1. 4. 13:29
728x90

▶55 - Jump Game

문제

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.

 

예제

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

 

풀이

dp를 이용하는 문제인데, dp의 값은 max(dp[i - 1] - 1, nums[i])가 된다.

이유는 각 칸이 점프할 수 있는 칸 수라서, 그냥 저렇게 넣었다.

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        if len(nums) == 1:
            return True
        dp = [0 for _ in range(len(nums))]
        dp[0] = nums[0]
        for i in range(1, len(nums)):
            dp[i] = max(dp[i - 1] - 1, nums[i])
        
        if 0 in dp[:-1]:
            return False
        else:
            return True

728x90