배움 저장소

[Leet Code]055 Jump Game 본문

PS/LeetCode

[Leet Code]055 Jump Game

시옷지읏 2021. 10. 6. 00:30

https://leetcode.com/problems/jump-game/submissions/

 

Jump Game - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

디버깅이 없었다면 이 문제를 못 풀었을 거 같다. 뭐가 문제인지 따라가보면서 확인하고 로직을 고치니 한결 수월했다. 이때까지 디버깅을 왜 안썼나 싶다.

class Solution {
public:
    bool canJump(vector<int>& nums) {
        saved_nums = nums;
        count = saved_nums.size()-1;
        return Jump(0);
    }

private:
    vector<int> saved_nums;
    int count;

    bool Jump(int cur)
    {
        // Validate Current Location
        if(cur + saved_nums[cur] >= count) return true;

        // Move Next Position
        // cur is always smaller than saved_nums.size() -1
        if(saved_nums[cur] == 0) return false;

        int maxReach = 1;
        int saved_i = -1;
        for(int i=1; i<=saved_nums[cur]; ++i)
        {
            if(cur+i > count) continue;
            if( i + saved_nums[cur+i] >= maxReach)
            {
                maxReach = i + saved_nums[cur+i];
                saved_i = cur+i;
            }
        }
        return saved_i==-1? false : Jump(saved_i);
    }
};
Comments