码迷,mamicode.com
首页 > 其他好文 > 详细

力扣 | 55. 跳跃游戏

时间:2019-11-18 18:17:44      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:false   商业   一个   type   solution   pen   nbsp   style   view   

给定一个非负整数数组,你最初位于数组的第一个位置。

数组中的每个元素代表你在该位置可以跳跃的最大长度。

判断你是否能够到达最后一个位置。

示例 1:

输入: [2,3,1,1,4]
输出: true
解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。
示例 2:

输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

用动态规划超时了WA!!!!

技术图片
class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        nums=nums[::-1]
        f=[0]*len(nums)
        f[-1]=1
        print(f)
        for i in range(len(nums)):
            for j in range(i):
                if f[j] and i-j<=nums[j]:#如果可以到达j位置,并且从j位置可以跳到i位置
                    f[i]=1
                    break
        return f[-1]

a=Solution()
print(a.canJump([2,3,1,1,4]))
View Code

借鉴了一波大佬的思路

class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        maxd = 0
        for i in range(len(nums)):
            if (i>maxd): return False
            maxd = max(maxd, i + nums[i])
        return True

 

 

力扣 | 55. 跳跃游戏

标签:false   商业   一个   type   solution   pen   nbsp   style   view   

原文地址:https://www.cnblogs.com/chrysanthemum/p/11883689.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!