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

這一題首先要認識到,到達索引小的點所需要的跳數肯定比到達索引大的點所需要的跳數要小。
然後這一題就是一個廣義搜索算法的題目。記錄跳數可以到達的下標範圍,由第一跳到達的點可以推出第二跳可以到達的點,以此類推,可以到達所有的點。當到達的某個跳數的點中含有最後一個點的時候即可結束算法,返回跳數。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章