[leetcode] 55. Jump Game

题目

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.

Example 1:

Input: nums = [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: nums = [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.

Constraints:

  • 1 <= nums.length <= 104
  • 0 <= nums[i] <= 105

思路

dfs遍历所有情况,超时。

贪婪算法,每个台阶的最大跳跃高度是i+nums[i],那么维护当前跳跃的最大高度,如果这个最大高度跳不上当前的台阶,就是失败。

代码

python版本:

# dfs,超时
class Solution:
    def canJump(self, nums: List[int]) -> bool:
        res = False

        def dfs(now):
            nonlocal res
            if res or now >= len(nums):
                return
            if now == len(nums)-1:
                res = True
                return
            [dfs(now+i) for i in range(nums[now], 0, -1)]
        dfs(0)
        return res

# 贪婪
class Solution:
    def canJump(self, nums: List[int]) -> bool:
        maxn = 0
        for i, num in enumerate(nums):
            if maxn < i:
                return False
            maxn = max(maxn, i+num)
        return True

# 贪婪2,从后到前
class Solution:
    def canJump(self, nums: List[int]) -> bool:
        goal = nums[-1]
        for i in range(len(nums))[::-1]:
            if i+nums[i] >= goal:
                goal = i
        return goal == 0

posted @ 2022-04-01 15:45  frankming  阅读(25)  评论(0编辑  收藏  举报