【LeetCode】Jumping Game II

  • The code written in the official solution is really concise! But the title is really rubbish.

1. Topic

insert image description here

2. Analysis

Greedy minds solve this problem!

3. Code

from  typing import List

class Solution:
    def jump(self, nums: List[int]) -> int:
        n = len(nums) 
        # maxPos 表示当前到达的最大位置
        # step 表示走了几次
        maxPos, end, step = 0, 0, 0
        for i in range(n - 1):
            # 这个是什么逻辑? => 表明在这个区间内可以更新maxPos
            # 那么 maxPos < i 会做什么操作?
            # 在整个区间,应该都有这个maxPos >= i
            if maxPos >= i:
                maxPos = max(maxPos, i + nums[i])
                if i == end: # 说明到这儿的的确确到头了,那就加一次step,同时更新maxPos
                   end = maxPos # 
                   step += 1
        return step

nums = [2,3,1,1,4]
s = Solution()
s.jump(nums)

disability

class Solution:
    def jump(self, nums: List[int]) -> int:
        dp = [99999]* len(nums)
        dp[0] = 0 # 第一步不用跳
        # 第i阶
        for i in range(len(nums)):
            step = nums[i]
            # 可以走 0 ~ step 
            for j in range(1,step+1):
                if i+j >= len(nums):
                    break
                if dp[i+j] == 99999:
                    dp[i+j] = dp[i] + 1
                    continue
                dp[i+j] = min(dp[i] + 1,dp[i+j])
        print(dp)
        return dp[-1]

Guess you like

Origin blog.csdn.net/liu16659/article/details/127001282