高级编程技术作业_13 leetcode练习题

55.Jump Game

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.

解题思路:

  采用递归的思想解题,如果数组中每个元素都大于0,则最后一个位置必定是可达的;
否则,找到最后一个值为0的位置,从这个位置i开始向前遍历,如果i是目的地,找到
一个位置j能够跳跃的步数大于等于位置i与j的距离,如果该位置j是可达的,则目的地
是可达的,若找不到这样的位置j,则目的地不可达;如果i不是目的地,找到一个位置j
能够跳跃的步数大于位置i与j的距离,如果该位置j是可达的,则目的地是可达的,若找
不到这样的位置j,则目的地不可达。

代码展示:

class Solution():
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        index = len(nums) - 1
        # if len(nums) == 1
        if index == 0:
            return True

        # check values of elements from the tail of list
        while index >= 0:
            if nums[index] == 0:
                # for a 0 in list, find if there is a position before it where could jump over it 
                for i in range(index - 1,-1,-1):
                    if index == len(nums) - 1:
                        if nums[i] >= index - i:
                            # if there is, find if this position is reachable
                            return self.canJump(nums[:i + 1])
                    elif nums[i] > index - i:
                        return self.canJump(nums[:i + 1])
                # or last index is not reachable
                return False
            index -= 1

        #if every element larger than 0, the last index is reachable
        return True

猜你喜欢

转载自blog.csdn.net/akago9/article/details/80149446