题目:
给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
示例 1:
输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。
示例 2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
个人思路:
按之前做的2来,在范围内不断找出可以跳的最远的下一跳直到终点。
官方答案推荐:
直接遍历数组,计算可以跳的最远位置,如果最远位置<当前位置则返回false,最远位置比数组长度大则返回true
python代码:
#自己写的麻烦代码
class Solution:
def canJump(self, nums: List[int]) -> bool:
endIndex = len(nums) - 1
#只有1个数的情况
if endIndex==0:
return True
curIndex = 0
while curIndex <= endIndex:
#下一个要移动的位置
nextIndex = curIndex
#当前数框出的可选范围,找一个可以跑的最远的位置
for i in range(curIndex+1,nums[curIndex]+curIndex+1):
if i >= endIndex:
return True
if nums[i]+i > nums[nextIndex]+nextIndex:
nextIndex = i
#前后没变,说明该位置是0,不可能成功
if nextIndex == curIndex:
return False
#移动到下一个位置
curIndex = nextIndex
#下一个位置跑的最远可以超过边界,返回true
if nums[nextIndex]+nextIndex >=endIndex:
return True
#按照官方答案来的,耗时差不多
class Solution:
def canJump(self, nums: List[int]) -> bool:
maxJump = 0
for curIndex,curJump in enumerate(nums):
if maxJump > len(nums):
return True
if maxJump < curIndex:
return False
maxJump = max(maxJump,curIndex+curJump)
return True
反思:
需要的不是不断遍历回溯,而是在每个位置移动时先计算出一个可以跳的最远的位置