[Leetcode/Python] Jump Game

지구인 ㅣ 2022. 11. 25. 10:13

728x90
Top Interview Questions 의 Easy Collection에 있는 문제입니다.         
문제는 여기서 볼 수 있습니다.

 

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.

 

Constraints:

  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 10^5

 

Code:

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        goal = len(nums) - 1
        # 끝 인덱스부터 탐색
        for i in range(len(nums)-1,-1,-1):
            # 만약 i번째에서 goal 인덱스까지 도달 가능 시
            # goal 재설정
            if i + nums[i] >= goal:
                goal = i
        return not goal

 

동적 계획법을 사용하되 끝 인덱스부터 탐색하는 방법으로 문제를 해결할 수 있다.

 

728x90

'알고리즘' 카테고리의 다른 글

[Leetcode/Python] Unique Paths  (0) 2022.11.29
[Leetcode/Python] Happy Number  (0) 2022.11.29
[Leetcode/Python] Binary Tree Inorder Traversal  (0) 2022.11.24
[Leetcode/Python] Missing Number  (0) 2022.11.21
[Leetcode/Python] Reverse Bits  (0) 2022.11.21