Leek55. Jumping Game [C++]

topic description

insert image description here

problem solving ideas

This question is easy to think too much, such as what to jump a few steps at a time, how to reach the end and so on. It's very complicated to think about it this way. Look carefully at the following questions. I didn't ask how many ways to jump. He doesn't care how you jumped over it. You just need to tell him whether you can jump over it.

Idea 1 (Unable to pass all test points)

Observing the two arrays given, we can draw a conclusion: as long as there is no 0 in the array, then we can jump over. If there is zero, judge whether the previous number is greater than two steps, and whether it can cross this 0.

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

		return true;
	}
};

insert image description here

Only 105 test points have passed. I feel that this idea is no problem, but I don’t know why it can’t pass all test cases.

Idea 2 (passable)

It is to record the number of steps he can jump, as long as the number of steps can be greater than the last subscript of the array, then he can jump over, otherwise he cannot jump over.

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

	}
};

insert image description here

Guess you like

Origin blog.csdn.net/qq_63524016/article/details/129494001