【leetcode hot 100 55】跳跃游戏

解法一:(递归)第i个位置要跳到第j个位置,得nums[i]>=j-i。因此倒叙,判断能跳到n-1的位置为location1->能跳到location1的位置为location2-> … ->能跳到0则true。

class Solution {
    public boolean canJump(int[] nums) {
        // 要跳到第j个位置,nums[i]>=j-i(注意要-i)
        int n = nums.length;
        // 要跳到n
        return canJump_helper(nums, n-1);
    }

    public boolean canJump_helper(int[] nums, int location){
        // location是现在在的位置
        if(location==0){
            return true;
        }
        for(int i=0; i<location; i++){
            if(nums[i]>=location-i){
                // 能跳
                return canJump_helper(nums, i);
            }
        }
        return false;
    }
}

注意:

  • 要跳到第location个位置,nums[i]>=location-i,这里不能是location,得是location-1

解法二:(贪心算法)我们依次遍历数组中的每一个位置,并实时维护最远可以到达的位置。在遍历的过程中,如果 最远可以到达的位置 大于等于数组中的最后一个位置,那就说明最后一个位置可达,我们就可以直接返回 True 作为答案。反之,如果在遍历结束后,最后一个位置仍然不可达,我们就返回 False 作为答案。

贪心算法(Greedy Algorithm)是一种在求解最优化问题时常用的算法策略。其核心思想是‌在每一步选择中都采取当前状态下最优的选择,以期望最终得到全局最优解‌。

解法三:不用递归,容易栈溢出

class Solution {
    public boolean canJump(int[] nums) {
        // 要跳到第j个位置,nums[i]>=j-i(注意要-i)
        int n = nums.length;
        // 要跳到n
        // location是现在在的位置
        int location =n-1;
        boolean isBreak;
        while(location>0){
            isBreak =false;
            for(int i=0; i<location; i++){
                if(nums[i]>=location-i){
                    // 能跳
                    location=i;
                    isBreak=true;
                    break;
                }
            }
            if(!isBreak){
                return false;
            }
        }
        return true;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值