2020-09-23

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所有点能达到索引的集合;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值