Leetcode算法——55、跳跃游戏

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HappyRocking/article/details/84535188

给定一个非负整数的数组,每一个元素表示从当前位置开始跳跃一次的最大长度。

你一开始站在第一个索引的位置。

判断你是否可以跳跃到最后一个索引位置。

示例:

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.

思路

递归法

如果从倒数第二位置可以跳到倒数第一位置,那么在这个前提下,可以跳跃到倒数第一位置 <=> 可以跳跃到倒数第二位置

证明:

  • 从左到右,明显成立,也不需要这个前提条件。因为每次不一定要跳最大步,既然可以跳到倒数第一的位置,那么可以跳近一点跳到倒数第二位置。
  • 从右到左,跳跃到第二位置之后,已知可以从倒数第二位置跳到倒数第一位置,因此可以跳跃到倒数第一位置。

因此,在这个前提下,原问题转化为:寻找是否可以跳跃到倒数第二位置。这里可以使用递归方法。

如果从倒数第二位置跳不到倒数第一位置,则继续向前寻找倒数第三位置是否可以一步跳到倒数第一位置,同理,可以转化为类似的等价问题。

依次向前查询,如果前面的元素全部都不能一步跳到倒数第一位置,则说明原问题的答案为 False

python实现

def canJump(nums):
    """
    :type nums: List[int]
    :rtype: bool
    递归法。
    """
    
    def can_reach(j):
        '''
        判断是否可以到达索引j
        '''
        # 递归结束条件
        if j == 0:
            return True
        # 从后向前开始扫描,只要有其中一个位置可以从它开始跳到j,就可以继续递归
        for i in range(j-1, -1, -1):
            if nums[i] >= j - i:
                return can_reach(i)
        return False
    
    return can_reach(len(nums)-1)

if '__main__' == __name__:
    nums = [3,2,1,0,4]
    print(canJump(nums))

猜你喜欢

转载自blog.csdn.net/HappyRocking/article/details/84535188