LeetCode.55 Jump Game (中等)greedy

topic

Given an array of non-negative integers, you are initially at the first position of the array. Each element in the array represents the maximum length you can jump at that position. Determine whether you can reach the last position.

Example 1:

输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。

Example 2:

输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 ,所以你永远不可能到达最后一个位置。
  • It can be violent, recursively by layer, each layer can jump one step or two steps or several steps up to the maximum number of jumping steps (when it is greater than 1), which layer its maximum number of steps can jump to, and then from that layer to the largest Jump the number of layers and search again, until the recursive termination condition (there is no candidate, the last element in the array). Exponential time complexity
  • Can be traced back
  • Can be dynamically planned

Here we use greed to solve (greed can be greedy from back to front, or it can be cut from a certain part to be greedy)

class Solution {
    
    
    public boolean canJump(int[] nums) {
    
    
        if(nums == null){
    
    
            return false;
        }

        int endReachable = nums.length - 1;
        for(int i = nums.length - 1;i>= 0;i--){
    
    
            if(i + nums[i] >= endReachable){
    
    
                endReachable = i;
            }
        }

        return endReachable == 0;
    }
}

endReachableRefers to the subscript that can reach the last position. Each time the for loop moves the subscript position, looping from back to front, it i + nums[i]means how far it can jump from the point i, if it can jump more than the last one can jump When the subscript of the final point is reached, update i to endReachable. endReachableIt always refers to the last point that the first subscript can jump to.

Finally, it endReachableis judged whether it is 0, and 0 means that the position of the first coordinate can also jump to the end, so the result is obtained.

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106945180