题目:
Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
题解:
class Solution:
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return 0
#jumps存放给定跳数可到达的下标,key是跳数,列表是可达下标列表
#jumps = {0 : [0],}
jumps = [[0], ]
flags = [0] * len(nums)
flags[0] = 1
jump = 0
while True:
jumps.append([])
#jumps[jump+1] = []
for index in jumps[jump]:
if index + nums[index] + 1 >= len(nums):
return jump + 1
i = index + nums[index]
while flags[i] == 0:
flags[i] = 1
jumps[jump+1].append(i)
i -= 1
jump += 1
这一题首先要认识到,到达索引小的点所需要的跳数肯定比到达索引大的点所需要的跳数要小。
然后这一题就是一个广义搜索算法的题目。记录跳数可以到达的下标范围,由第一跳到达的点可以推出第二跳可以到达的点,以此类推,可以到达所有的点。当到达的某个跳数的点中含有最后一个点的时候即可结束算法,返回跳数。