高级编程技术作业_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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值