Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode: 跳跃游戏 #22

Open
HeyShinner opened this issue Feb 8, 2020 · 2 comments
Open

LeetCode: 跳跃游戏 #22

HeyShinner opened this issue Feb 8, 2020 · 2 comments

Comments

@HeyShinner
Copy link
Owner

https://leetcode-cn.com/problems/jump-game/

@HeyShinner
Copy link
Owner Author

HeyShinner commented Feb 8, 2020

  • 时间复杂度计算

@HeyShinner
Copy link
Owner Author

HeyShinner commented Feb 8, 2020

  • 方法一:回溯
var canJump = function(nums) {
  return canJumpFromPos(0, nums);
};

function canJumpFromPos(pos, nums) {
    if (pos === nums.length - 1) {
      return true;
    }
    let furtherJump = Math.min(pos + nums[pos], nums.length - 1);
    for (let nextPos = furtherJump; nextPos > pos; nextPos --) {
      if (canJumpFromPos(nextPos, nums)) {
        return true;
      }
    }
    return false;
  }

时间复杂度为什么是 O(2^n)

  • 方法二:自顶向下的动态规划
var canJump = function(nums) {
  const memo = new Array(nums.length);
  for (let i = 0; i < memo.length; i ++) {
    memo[i] = 'unkonwn';
  }
  memo[memo.length - 1] = 'good';
  
  const canJumpFromPos = (pos, nums) => {
    if (memo[pos] !== 'unkonwn') {
      return memo[pos] === 'good' ? true : false;
    }
    let furtherJump = Math.min(pos + nums[pos], nums.length - 1);
    for (let nextPos = furtherJump; nextPos > pos; nextPos --) {
      if (canJumpFromPos(nextPos, nums)) {
        memo[pos] = 'good';
        return true;
      }
    }
    memo[pos] = 'bad';
    return false;
  }

  return canJumpFromPos(0, nums);
};

时间复杂度 O(n^2)

  • 自底向上的动态规划
  • 贪心

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant