0
点赞
收藏
分享

微信扫一扫

LeetCode-045-跳跃游戏 II

Mezereon 2021-09-28 阅读 65
LeetCode

跳跃游戏 II

解法一:穷举法
import java.util.*;

public class LeetCode_045 {
    public static int jump(int[] nums) {
        if (nums.length == 1) {
            return 0;
        }
        if (nums.length == 2) {
            return 1;
        }
        int result = Integer.MAX_VALUE;
        int length = nums.length - 1;
        // 定义走到过的位置,并且记录走到当前位置最少的步数
        Map<Integer, Integer> toJumpTimes = new HashMap<>();
        toJumpTimes.put(0, 0);
        // 定义当前到的位置
        Stack<Integer> toJump = new Stack<>();
        Stack<Integer> times = new Stack<>();
        toJump.push(0);
        times.push(0);
        while (!toJump.isEmpty()) {
            Integer cur = toJump.pop();
            Integer curTimes = toJumpTimes.get(cur);
            if (nums[cur] == 0) {
                continue;
            }
            // 判重,如果走到当前位置的步数多于其他走法走到当前位置的步数,则跳过处理下一个
            if (toJumpTimes.containsKey(cur) && curTimes > toJumpTimes.get(cur)) {
                continue;
            }
            if (nums[cur] >= length - cur) {
                if (curTimes + 1 < result) {
                    result = curTimes + 1;
                }
            } else {
                if (curTimes + 1 >= result) {
                    continue;
                }
                for (int i = 1; i <= nums[cur]; i++) {
                    if (!toJumpTimes.containsKey(cur + i)) {
                        if (curTimes + 1 < result) {
                            toJumpTimes.put(cur + i, curTimes + 1);
                            toJump.push(cur + i);
                            times.push(curTimes + 1);
                        }
                    } else {
                        Integer time = toJumpTimes.get(cur + i);
                        if (curTimes + 1 < time) {
                            toJumpTimes.put(cur + i, curTimes + 1);
                            toJump.push(cur + i);
                            times.push(curTimes + 1);
                        }
                    }
                }
            }
        }
        return result;
    }

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

相关推荐

0 条评论