代码改变世界

[LeetCode] 55. Jump Game_ Medium tag: Dynamic Programming

2019-04-24 10:35  Johnson_强生仔仔  阅读(325)  评论(0编辑  收藏  举报

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.

Determine if you are able to reach the last index.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.

这个题目因为是问的yes/no,然后跟坐标有关(也就是说如果数组里面有数字互相调换了答案就不一样了),很有可能是dynamic programming,这里用动态规划来做。f(i) 表示能否跳到该点,function 用
f(i) = true if f(j) and nums[j] >= i - j (for loop), 一旦有就break,这里可以稍微improve一点时间上的效率。
T: O(n^2) S: O(n)
note:但是在leetcode上面这个会limit time exceed。

08/07/2021 Update: Greedy O(n)

Code:
class Solution:
    def jumpGame(self, nums):
        if not nums: return False
        n = len(nums)
        mem = [False] * n
        mem[0] = True
        for i in range(1, n):
            for j in range(i - 1, -1, -1):
                if mem[j] and nums[j] >= i - j:
                    mem[i] = True
                    break
        return mem[-1]

 

Greedy O(n) ideas: 

1. 从右边往左边推, 初始化lastGoodIndex = n - 1

2. 再从n - 2 开始往前面推, 看当前的index的数值nums[index] >= lastGoodIndex index  - index, 如果可以那当前的index是good index

3. 不停更新lastGoodIndex index

4. 最后check lastGoodIndex 是否为0

 

Code 2: 

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        n = len(nums)
        lastGoodIndex = n - 1
        for i in range(n - 2, -1, -1):
            if (i + nums[i] >= lastGoodIndex):
                lastGoodIndex = i
        return lastGoodIndex == 0