LeetCode第55题 - 跳跃游戏

题目

解答一

java 复制代码
class Solution {   
    public boolean canJump(int[] nums) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        if (nums[0] == 0 && nums.length == 1) {
            return true;
        }
        return canJump(nums, 0);
    }

    public boolean canJump(int[] nums, int index) {
        if (index > nums.length - 1) {
            return false;
        }
        if (nums[index] == 0) {
            return false;
        }

        if (nums[index] + index >= nums.length - 1) {
            return true;
        }

        // for (int i = 1; i <= nums[index]; ++i) {
        for (int i = nums[index]; i > 0; --i) {
            if (canJump(nums, index + i)) {
                return true;
            }
        }

        return false;
    }
}

解答二

java 复制代码
class Solution {
    public boolean canJump(int[] nums) {
        int max = 0;
        for (int i = 0; i < nums.length && i <= max; i++) {
            max = Math.max(max, i + nums[i]);
            if (max >= nums.length - 1) {
                return true;
            }
        }

        return false;
    }
}

总结

解答一使用递归,可以解决问题,但当输入规模增大时,可能出现递归过多、栈溢出的现象,同时效率也不满足要求。

解决二使用贪心算法,简单、直接、暴力、有效。变量max的使用,值得深入理解。

相关推荐
政企项目老覃40 分钟前
大模型幻觉治理与自动评测:金融风控场景的落地实践
人工智能·算法·机器学习
淡海水1 小时前
08-03-不可变-ImmutableDictionary-TKey-TValue-与ImmutableHashSet-T-持久化哈希树
数据结构·算法·c#·哈希算法·dictionary·immutable
hansang_IR1 小时前
【题解】[APIO2023] 赛博乐园 / cyberland
c++·算法·图论
洛阳纸贵1 小时前
MATLAB-matlab基础知识
学习·算法·matlab
落羽的落羽2 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Nil2082 小时前
leetcode 17电话号码的字母组合
算法·leetcode·职场和发展
203号居民3 小时前
LeetCode hot 100 — 25. K 个一组翻转链表
算法·leetcode·链表
ocean21034 小时前
2025-2026年AI算法与模型研发面试高频知识点洞察
人工智能·算法·面试
Nil2084 小时前
leetcode 78子集
数据结构·算法·leetcode