【Leetcode】55. 跳跃游戏

234 阅读1分钟

题目描述

在这里插入图片描述

// 55. 跳跃游戏

// 给定一个非负整数数组 nums ,你最初位于数组的 第一个下标 。
// 数组中的每个元素代表你在该位置可以跳跃的最大长度。
// 判断你是否能够到达最后一个下标。



题解

// 刚开始想到回溯搜索法,但是时间复杂度超了。
class Solution {
    boolean res = false;
    public boolean canJump(int[] nums) {
        backtracking(nums, nums[0], 0);
        return res;
    }

    private void backtracking(int[] nums, int step, int start) {
        if (step + start >= nums.length - 1) {
            res = true;
        }
		for (int i = start + 1; i <= Math.min(start + step, nums.length - 1); i++) {
			backtracking(nums, nums[i], i);
		}
    }
}


// 贪心算法
// 假设for循环遍历的索引为i,遍历元素(跳的步幅)为nums[i],我们其实只需要关心
// 跳跃范围内数值最大的那个数,因此定义最大跳跃范围stepMax,初始化为0,
// for循环遍历,索引为i,遍历元素为nums[i],在保证i不超过最大跳跃范围stepMax的
// 情况下,取for循环遍历过程中,nums[i] + i的最大值与stepMax比对赋给stepMax,
// 这就得到了最大跳跃范围内的元素最大值,
// 之后每次更新stepMax都要判断一下,所得到的stepMax能不能达到len-1这个位置,
// 达到了就返回true。如果循环结束都找不到能够超过len-1的最大跳跃范围stepMax,
// 返回false。
// 
// 执行用时:2 ms, 在所有 Java 提交中击败了83.16%的用户
// 内存消耗:40.6 M, 在所有 Java 提交中击败了12.60%的用户
class Solution {
    public boolean canJump(int[] nums) {
		int len = nums.length;
		int stepMax = 0;
		for (int i = 0; i < len; i++) {
			if (i <= stepMax) {
				stepMax = Math.max(stepMax, nums[i] + i);
				if (stepMax >= len - 1)
					return true;
			}
		}
		return false;
    }
}