贪心法-Jump Game

本文探讨了数组跳跃问题的三种解决方案,分别使用了动态规划、逆向遍历和优化后的正向遍历方法,旨在判断能否从数组起始位置达到末尾。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个数组,每个数组元素的值为最大的跳跃值,求是否能从数组0元素到数组最大的元素

public static bool canJump2(int[] nums)
        {
            int[] f = new int[nums.Length];
            for(int i = 1; i < nums.Length; i++)
            {
                f[i] = Math.Max(f[i - 1], nums[i - 1]) - 1;
                if (f[i] < 0) return false;
            }
            return f[nums.Length - 1] >= 0;
        }

        public static bool canJump1(int[] nums)
        {
            if(nums.Length==0)return true;
            int left_most = nums.Length - 1;
            for(int i = nums.Length - 2; i >= 0; --i)
            {
                if (i + nums[i] >= left_most)
                {
                    left_most = i;
                }
            }
            return left_most == 0;
        }

        public static bool canJump(int[] nums)
        {
            int reach = 1;
            for(int i=0;i<reach && reach < nums.Length; ++i)
            {
                reach = Math.Max(reach, i + 1 + nums[i]);
            }
            return reach >= nums.Length;
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值