【LeetCode】解题55:Jump Game

Problem 55: Jump Game [Medium]

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.

来源:LeetCode

解题思路

解题思路类似Problem 45: Jump Game II
利用贪心算法的思想:
一个点选择下一个跳跃点的原则为:下一个跳跃点能够跳的最远。可以解释为,如果跳得最远的点都跳不到数组末尾,那么结果必然是false。
在每个位置index的搜索过程中,选择下一个跳跃点的公式为:
n e x t _ p o i n t = arg max ⁡ i { i + n u m s [ i ] } next\_point = \argmax_i\{i + nums[i]\}\\ next_point=iargmax{i+nums[i]}
其中, i ∈ [ i n d e x + 1 , i n d e x + n u m s [ i n d e x ] ] i \in [index + 1, index + nums[index]] i[index+1,index+nums[index]],然后对 n e x t _ p o i n t next\_point next_point进行递归搜索。

具体过程:

  • 使用递归搜索,从index=0开始,直到index + nums[index] >= N-1时结束,每次返回下一步递归结果。
  • 在每个位置index的搜索过程中,搜索范围为当前位置能够跳跃的范围(index+1 ~ index + nums[index]),在该范围中找到一个能够在未来跳得最远的点,作为下一层递归的起始点。如果没有比本身跳得更远的,则不改变index的值。
  • 递归结束条件:
    a. 当前点能够一步跳到数组末尾(index + nums[index] >= N-1),直接返回true。
    b. 在搜索下一个跳跃点时,发现跳跃范围内有点可以一步跳到数组末尾,直接返回true。
    c. 发现下一个跳跃点永远是本身,即下一步没有能跳得更远的选择,说明永远跳不到数组末尾,直接返回false。

运行结果:
在这里插入图片描述

Solution (Java)

class Solution {
    public boolean canJump(int[] nums) {
        int N = nums.length;
        if(N == 0 || N == 1) return true;
        if(N == 2) return (nums[0] != 0);
        return max_len(0, nums, N);
    }
    private boolean max_len(int start, int[] nums, int N){
        if(start + nums[start] >= N - 1) return true;
        int max = start + nums[start];
        int next_start = start;
        for(int i = start + 1; i <= start + nums[start]; i++){
            if(i + nums[i] >= N - 1) return true;
            if(i + nums[i] > max){
                max = i + nums[i];
                next_start = i;
            }
        }
        if(next_start == start) return false;
        return max_len(next_start, nums, N);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值