递归方式,会造成栈溢出

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
/**
 * @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;
};

循环方式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
/**
 * @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;
};