python学习第8周(1):LeetCode45. Jump Game II题解

 

题目:

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

这一题首先要认识到,到达索引小的点所需要的跳数肯定比到达索引大的点所需要的跳数要小。
然后这一题就是一个广义搜索算法的题目。记录跳数可以到达的下标范围,由第一跳到达的点可以推出第二跳可以到达的点,以此类推,可以到达所有的点。当到达的某个跳数的点中含有最后一个点的时候即可结束算法,返回跳数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值