Leetcode 55. Jump Game

题目

Leetcode 55. Jump Game_第1张图片

解法1:dfs+memorization (TLE)

照例来讲这种解法应该是o(n)的但是不知道为啥会超时,莫非是我时间复杂度估计得不对?

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        def dfs(curr_pos,n):
            if curr_pos >= n:
                return False
            # check if we reached the end
            if curr_pos == n - 1:
                return True
            # mark current position as visited
            visited[curr_pos] = 1
            # check every possible step from current position
            for step in range(1,nums[curr_pos]+1):
                if curr_pos + step >= n or visited[curr_pos+step] == 1:
                    continue
                if dfs(curr_pos+step,n):
                    return True
            return False
                
            return reached
        n = len(nums)
        if n == 1:
            return True
        visited = [0] * n
        return dfs(0,n)

解法2:

直接判断是否当前位置加上步数会比最后一个位置大。同时keep track当前能到达的最远位置

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        n = len(nums)
        curr_far = 0
        for i in range(n):
            if i > curr_far:
                return False
            curr_far = max(i+nums[i],curr_far)
        return curr_far >= n-1

你可能感兴趣的:(Leetcode,贪心(greedy),Leetcode,DFS,Leetcode,模拟,leetcode,深度优先,算法)