跳跃游戏 II

题目描述:给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

你的目标是使用最少的跳跃次数到达数组的最后一个位置。

假设你总是可以到达数组的最后一个位置。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-ii/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:穷举法
  • 首先,如果nums的长度为1,因为不需要走,直接返回0;
  • 如果nums的长度为2,由于一定可以到达最后一个位置,而且至少需要一步,直接返回1;
  • 当不是前两种情况时,首先,声明一个变量length为数组最大的索引位,声明一个变量result记录最少的跳跃次数,初始化为最大的的int值,声明一个HashMap为toJumpTimes记录跳跃过的位置和相应跳跃到该位置最少的步数,声明一个队列toJump记录当前走到的位置,声明一个队列times同步记录走到当前位置需要的步数,首先,将0加入到jumped和times,然后遍历队列toJump按照以下过程处理:
    • 从队列中取出一位cur;
    • 如果cur对应的数组的值为0,则跳过处理下一个队列中的值;
    • 判断toJumpTimes中是否存在该位置的索引,如果存在且走到当前位置的步数多于其他走法走到当前位置的步数,则跳过处理下一个;
    • 如果cur对应的数组的值大于等于length-cur即可以从当前位置直接跳跃到最后一位,则判断如果当前的跳跃次数小于result,则更新result的值;
    • 否则,如果当前跳跃次数不小于result,则跳过处理下一个;如果当前跳跃次数小于result,则将cur+1 ~ cur+nums[cur]索引位添加到toJump,添加之前需要判断toJumpTimes的key中是否存在当前索引位:
      • 如果不存在并且当前跳跃次数小于result,则把当前索引位和相应的跳跃次数添加到toJump和times和toJumpTimes;
      • 如果存在并且当前跳跃次数小于最小的跳跃次数,则把当前索引位和相应的跳跃次数添加到toJump和times,并且更新当前索引位在toJumpTimes中的最少跳跃次数。

最后,返回result即为最少跳跃次数。

说明:处理方法类似于 LeetCode-055-跳跃游戏 这道题目。

  1. import java.util.*;
  2. public class LeetCode_045 {
  3. public static int jump(int[] nums) {
  4. if (nums.length == 1) {
  5. return 0;
  6. }
  7. if (nums.length == 2) {
  8. return 1;
  9. }
  10. int result = Integer.MAX_VALUE;
  11. int length = nums.length - 1;
  12. // 定义走到过的位置,并且记录走到当前位置最少的步数
  13. Map<Integer, Integer> toJumpTimes = new HashMap<>();
  14. toJumpTimes.put(0, 0);
  15. // 定义当前到的位置
  16. Stack<Integer> toJump = new Stack<>();
  17. Stack<Integer> times = new Stack<>();
  18. toJump.push(0);
  19. times.push(0);
  20. while (!toJump.isEmpty()) {
  21. Integer cur = toJump.pop();
  22. Integer curTimes = toJumpTimes.get(cur);
  23. if (nums[cur] == 0) {
  24. continue;
  25. }
  26. // 判重,如果走到当前位置的步数多于其他走法走到当前位置的步数,则跳过处理下一个
  27. if (toJumpTimes.containsKey(cur) && curTimes > toJumpTimes.get(cur)) {
  28. continue;
  29. }
  30. if (nums[cur] >= length - cur) {
  31. if (curTimes + 1 < result) {
  32. result = curTimes + 1;
  33. }
  34. } else {
  35. if (curTimes + 1 >= result) {
  36. continue;
  37. }
  38. for (int i = 1; i <= nums[cur]; i++) {
  39. if (!toJumpTimes.containsKey(cur + i)) {
  40. if (curTimes + 1 < result) {
  41. toJumpTimes.put(cur + i, curTimes + 1);
  42. toJump.push(cur + i);
  43. times.push(curTimes + 1);
  44. }
  45. } else {
  46. Integer time = toJumpTimes.get(cur + i);
  47. if (curTimes + 1 < time) {
  48. toJumpTimes.put(cur + i, curTimes + 1);
  49. toJump.push(cur + i);
  50. times.push(curTimes + 1);
  51. }
  52. }
  53. }
  54. }
  55. }
  56. return result;
  57. }
  58. public static void main(String[] args) {
  59. int[] nums = new int[]{2, 3, 1, 1, 4};
  60. System.out.println(jump(nums));
  61. }
  62. }

【每日寄语】 要铭记在心:每天都是一年中最美好的日子。