Home LeetCode - 55. Jump Game
Post
Cancel

LeetCode - 55. Jump Game

55. Jump Game - medium

문제

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

제한사항

입출력 예

1
2
3
4
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
1
2
3
4
5
Example 2:
Input: [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, Greedy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    bool canJump(vector<int>& nums) {
        int dis = 0;
        
        // index 0 부터 현재 index에서 점프할수 있는 최대 점프한 뒤의 index까지 반복
        // 반복을 수행하며 index i는 하나씩 증가하며,
        // 점프할수 있는 최대 거리의 index 또한 증가하는 index i의 값을 통해 변함
        for (int i = 0; i <= dis; ++i) {
            // 현재까지의 구한 최대 거리 index 와 index에서 갈수 있는 최대 점프후 도착하는 위치의 index를 비교
            // input = [2,3,1,1,4] 이며, i = 0, dis = 0 일때,
            // dis = max(0, 2+0) = 2
            // dis가 2가 되면서 반복문을 최대 2까지 반복할수 있음
            // 즉 점프할수 있는거리가 2까지 늘어나게됨
            dis = max(dis, nums[i] + i);
            
            // 저장한 현재 거리가 vector의 인덱스보다 크면 참
            if(dis >= nums.size() - 1)
                return true;
        }
        
        return false;
    }
};
This post is licensed under CC BY 4.0 by the author.