给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
示例:
输入: [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。从下标为 0 跳到下标为 1 的位置,跳1步,然后跳 3步到达数组的最后一个位置。
# 思路:动态规划--备忘录
class Solution:
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
length:跳跃的总长度
step+nums[i]:当前剩余步数
max(step, nums[i]):选择最大剩余步数
"""
n = len(nums)
if n == 1:
return 0
step = 0
start = 0 # 下次跳跃的起始位置
limit = 0 + nums[0] # 本次跳跃能跳到的最大位置
maxpos = 0 # 下次跳跃能跳到的最大位置
for i in range(n):
p = i + nums[i]
if p > maxpos:
maxpos = p
jump_pt = i
if maxpos >= n - 1: # 如果能到达终点则停止继续搜索
lastpoint = i # 最后一个起跳点
break
if i == limit: # 如果遍历到本次跳跃的最大位置依然还不能到达终点,那么必须开始下一次跳跃
limit = maxpos # 更新下一次跳跃的最大位置
start = jump_pt # 更新下一次跳跃的起跳点
step += 1
if start != lastpoint: # 必须先从start跳到lastpoint,再从lastpoint跳到终点
step += 2
else: # 当start与lastpoint重合时,只需跳一次。当且仅当start=lastpoint=0时成立
step += 1
return step