[Leetcode]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.

For example:
Given array A = [2,3,1,1,4]

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.)

Jump Game的擴展題~要求返回到達終點的最少步數~比較直觀的方法是用動態規劃,但是Leetcode過不了,Time Limit Exceeded~代碼如下~

dp[i]表示到第i個元素需要的最少步數,遞推公式是dp[i] = min(dp[j]) + 1 where 0 <= j < i and j + A[j] >= i~時間複雜度爲O(n^2)

class Solution:
    # @param A, a list of integers
    # @return an integer
    def jump(self, A):
        dp = [0] * len(A)
        for i in xrange(1, len(A)):
            minJump = (1 << 31) - 1
            for j in xrange(i):
                if j + A[j] < i:
                    continue
                else:
                    minJump = min(minJump, dp[j])
            dp[i] = minJump + 1
        return dp[len(A) - 1]

看了一些別人的解法,是用greedy algorithm~可是自己一直對貪婪算法沒理解透徹~用貪心算法的時間複雜度爲O(n)~代碼如下~

lastReach表示從A[0]進行minJump次jump之後達到的最大範圍; reach表示從0~i這i+1個A元素中能達到的最大範圍

當lastReach < i時,說明minJump次已經不足以覆蓋當前第i個元素,因此需要增加一次jump,使之達到

class Solution:
    # @param A, a list of integers
    # @return an integer
    def jump(self, A):
        if A is None or len(A) == 0: return 0
        minJump = 0; lastReach = reach = 0
        for i in xrange(len(A)):
            if lastReach < i:
                minJump += 1
                lastReach = reach
            reach = max(reach, A[i] + i)
        return 0 if reach < len(A) - 1 else minJump

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