0
点赞
收藏
分享

微信扫一扫

LeetCode-055-跳跃游戏

半夜放水 2021-09-28 阅读 48
LeetCode

跳跃游戏

解法一:穷举法
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

public class LeetCode_055 {
    public static boolean canJump(int[] nums) {
        if (nums.length == 1) {
            return true;
        }
        if (nums[0] == 0) {
            return false;
        }
        int length = nums.length - 1;
        // 定义走到过的位置
        Set<Integer> jumped = new HashSet<>();
        jumped.add(0);
        // 定义当前到的位置
        Queue<Integer> toJump = new LinkedList<>();
        toJump.add(0);
        while (!toJump.isEmpty()) {
            Integer cur = toJump.poll();
            jumped.add(cur);
            if (nums[cur] == 0) {
                continue;
            }
            if (nums[cur] >= length - cur) {
                return true;
            } else {
                for (int i = nums[cur]; i >= 1; i--) {
                    if (!jumped.contains(cur + i) && !toJump.contains(cur + i)) {
                        toJump.add(cur + i);
                    }
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{2, 3, 1, 1, 4};
        System.out.println(canJump(nums));
    }
}
举报

相关推荐

0 条评论