leetcode 未解决|55. Jump Game

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.

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.

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.

从第一步开始跳,该位置的坐标值为下一步跳的最大长度,问能否跳到最后

最初想的是直接通过一维的方法来跳,跳不下去了就往回挪下标(通过--),但是越写错误越多,有时候往回挪一次不行,需要更多次,遂放弃。


solution解答

1.回溯法

class Solution {
    public boolean canJumpFromPosition(int position,int[]nums){
        if(position==nums.length-1)
            return true;
        
        int furthestJump=Math.min(position+nums[position],nums.length-1);
        for(int nextPosition=position+1;nextPosition<=furthestJump;nextPosition++){
            //这里的nextposition是下标,所以还要加上position
            if(canJumpFromPosition(nextPosition,nums))
                return true;
        }
        return false;
    }
    public boolean canJump(int[] nums) {
        return canJumpFromPosition(0,nums);
    }
}

一步一步的往前跳,但这种方法时间复杂度过高,溢出了

2.回溯法+贪心算法

每一步先跳到能跳到的最远距离,跳不到终点再继续减

class Solution {
    public boolean canJumpFromPosition(int position,int[]nums){
        if(position==nums.length-1)
            return true;
        
        int furthestJump=Math.min(position+nums[position],nums.length-1);
        for(int nextPosition=furthestJump;nextPosition>position;nextPosition--){
            if(canJumpFromPosition(nextPosition,nums))
                return true;
        }
        return false;
    }
    public boolean canJump(int[] nums) {
        return canJumpFromPosition(0,nums);
    }
}

猜你喜欢

转载自blog.csdn.net/xueying_2017/article/details/81475267