跳跃游戏

Leetcode
2019-11-28 01:56

递归方式,会造成栈溢出

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var canJump = function(nums) {
  let maxIndex = nums.length - 1;
  for (let i = maxIndex - 1; i >= 0; i--) {
    const value = nums[i];
    if (value >= maxIndex - i) {
      maxIndex = i;
    }
  }
  return !maxIndex;
};

循环方式

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var canJump = function(nums) {
  const length = nums.length;
  if (length === 1) {
    return true;
  }

  for (let i = length - 2; i >= 0; i--) {
    const value = nums[i];
    if (value >= length - i - 1) {
      return canJump(nums.slice(0, i));
    }
  }
  return false;
};
验证码