Leetcode 45&55. Jump Game I &II

There are many solutions for these two problems. For Jump Game I, greedy is the best method, but we can also use DP to solve it.

Jump Game I

Solution 1 DP

There are two kind of DP solution, bottom-up and top-down. Reference: https://leetcode.com/problems/jump-game/solution/

Solution 2 Greedy
Special case: 023
If index<=reach is lost, this will return true.

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

Jump Game II

class Solution(object):
    def jump(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        last=0
        reach=0
        jump=0
        for i in range(len(nums)):
            if last<i:
                last=reach
                jump+=1
            reach=max(reach,nums[i]+i)
        return jump

猜你喜欢

转载自blog.csdn.net/u014731993/article/details/84981618