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
'LeetCode' 카테고리의 다른 글
[LeetCode] Medium - 452 Minimum Number of Arrows to Burst Balloons (0) | 2023.01.05 |
---|---|
[LeetCode] Medium - 1834 Single-Threaded CPU (0) | 2023.01.04 |
[LeetCode] Easy - 520 Detect Capital (0) | 2023.01.02 |
[LeetCode] Easy - 290 Word Pattern (0) | 2023.01.02 |
[LeetCode] Hard - 980 Unique Paths III (1) | 2022.12.31 |