LeetCode 55 Jump Game

The topics are as follows:

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.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.

After seeing the question, the first idea is to judge whether each position (i) can add the maximum jump distance (A[i]) to reach n-1 (array length minus 1), if not, then traverse i+( 1 ~A[i] ) these positions, and then recursively judge,
the following is the code:

class Solution {
public:
    int c[100000]={0};
    bool canJump(vector<int>& nums) {
        return sss(nums, 0);
    }
    bool sss(vector<int>& nums, int cur){
        c[cur] = 1;
        if(cur + nums[cur] >= nums.size()-1) return true;
        if(cur == nums.size()-1) return true;
        if(nums[cur] == 0) return false;
        for(int i = nums[cur]; i>=1;i--){
            if(c[cur+i] == 1) continue;
            if(sss(nums, cur+i)) return true;
        }
        return false;
    }
};

A large array is used to save the positions that have been run,,, otherwise the last test will be TLE,,,
not surprisingly, the efficiency is extremely low,,,

write picture description here

Then I found that there is no need for recursion, just start from position 0 to determine whether the farthest distance that can be reached is greater than or equal to n-1.
When traversing, pay attention to updating the maximum distance, and pay attention to whether the current position i can be reached, that is, less than or equal to the recorded maximum distance.
Attach the code~

bool canJump(vector<int>& nums) {
        if(nums.size() == 1) return true;
        int max=0;
       for(int i = 0; i < nums.size();i++){
           if(i > max) return false;
           if(i + nums[i] >= nums.size()-1) return true;
           max = i+nums[i] > max?i+nums[i]:max;
       }
       return false;
    }

Efficiency is much better. . .

write picture description here

The time is a lot less, but it can be seen that it is still not up to the level of most people, and more exchanges are needed for reference QwQ

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325564022&siteId=291194637