55. Jump Game

超时的递归做法:

class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) <= 1:
            return True
        can = self.bfs(nums,0)
        return can
        
    def bfs(self, nums, index):
        if index == len(nums) - 1:
            return True
        flag = False
        if nums[index] == 0:
            return False
        for i in range(1,nums[index]+1):
            if index + i <= len(nums) - 1:
                flag |= self.bfs(nums, index+i)
        return flag

依然超时的数组做法:

class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) <= 1:
            return True
        f = [0 for i in range(len(nums))]
        f[0] = 1
        for i in range(len(nums)):
            if f[i] != 0:
                for j in range(1,nums[i]+1):
                    if i+j < len(nums):
                        f[i+j] = 1
        if f[-1]:
            return True
        else:
            return False

AC的做法:
维护一个最远可以到达的指针

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

你可能感兴趣的:(55. Jump Game)