Leetcode45 跳跃游戏:最短跳跃路径记忆搜索
# -*- coding: utf-8 -*-
class Solution:
def solve(self, arrays):
length = len(arrays)
result, stack = [], [0]
left, right = 0, 0
while stack and right < length-1:
print('(left, right): {}, stack: {}, result: {}'.format((left, right), stack, result))
count, curmax = len(stack), right
for _ in range(count):
current = stack.pop(0)
value = arrays[current]
for ind in range(value+1):
distance = current + ind
if distance > right:
left, right = current, distance
if distance > curmax and distance < length:
stack.append(distance)
result.append(left)
if right >= length - 1:
result.append(length-1)
return result
else:
return []
if __name__ == "__main__":
arrays = [2, 0, 1, 3, 1, 2, 2, 4, 0, 0, 1, 2, 1]
solu = Solution()
print(solu.solve(arrays))
结果显示:
(left, right): (0, 0), stack: [0], result: []
(left, right): (0, 2), stack: [1, 2], result: [0]
(left, right): (2, 3), stack: [3], result: [0, 2]
(left, right): (3, 6), stack: [4, 5, 6], result: [0, 2, 3]
(left, right): (6, 8), stack: [7, 7, 8], result: [0, 2, 3, 6]
(left, right): (7, 11), stack: [9, 10, 11, 9, 10, 11], result: [0, 2, 3, 6, 7]
[0, 2, 3, 6, 7, 11, 12]
while 循环每一次代表跳跃1次/2次/3次…能达到的最远距离,并保留最远距离所对应的索引,分别用left和right来表示索引与最远距离;
stack: 初始点从索引0点开始;arrays[0]=2,可以跳到索引1与索引2,所以更新stack为[1, 2],即stack更新为上一个stack所有点能达到索引的集合;