4.25python Leetcode 45

45Jump 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.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
    Jump 1 step from index 0 to 1, then 3 steps to the last index.

Note:

You can assume that you can always reach the last index.

class Solution(object):
    def jump(self, nums):
        if len(nums) == 1:
            return 0
        ans = 0
        start = 0
        while start < len(nums) and start + nums[start] < len(nums) - 1:
            tmp_list = nums[start + 1: start + nums[start] + 1]
            i = 0
            max_jump = 0
            max = 0
            while i < nums[start]:
                if start + i + 1 + tmp_list[i] > max_jump and nums[start + i + 1 + tmp_list[i]]:
                    max = i + start + 1
                    max_jump = start + i + 1 + tmp_list[i]
                i += 1
            start = max
            ans += 1
        return ans + 1

        
        """
        :type nums: List[int]
        :rtype: int

 題解:

題目是給定一個列表nums, 給定下標i, nums[i]表示能從這個地方前進的最大步數。

現在從下標0開始,求到最後一個下標的最小步數。

第一想法是用動態規劃,即用一個所有值均爲無限大的數組step,用於存到這個位置所用的最小步數。

那麼對於每一個i, k <= nums[i], step[i+k] = min(step[i] + 1, step[i+k])

但是發現會超時,仔細一想最壞的情況是O(n平方)的。

因此,換一個想法,使用貪心算法。

即對於一個當前位置i, 只需要找到他的下2跳能到的最遠的位置即可。

即下一個位置應該爲j = max{i + k + nums[i + k], 1 <= k <= nums[i] }

當然,要證明這一點。倘若存在一個這樣的m不滿足這個等式,即m < j,但是通過這個m的到達終點的步數更少。

那麼在對於取定這個j的k,在下一跳的位置i+k中,根據算法的定義是一定不會漏掉這個m的,因此矛盾。

所以這個算法是可行的。


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