贪心法-Jump Game

给定一个数组,每个数组元素的值为最大的跳跃值,求是否能从数组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;
        }


猜你喜欢

转载自blog.csdn.net/smj20170417/article/details/80610583