Leetcode - 45. 跳跃游戏 II
给你一个非负整数数组
nums,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
你的目标是使用最少的跳跃次数到达数组的最后一个位置。
假设你总是可以到达数组的最后一个位置。
示例 1:
输入: nums = [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
示例 2:
输入: nums = [2,3,0,1,4]
输出: 2
提示:
- 1 <= nums.length <= 104
- 0 <= nums[i] <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/jump-game-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解1 2021/9/7 O(n)
def jump(nums: list) -> int:
# dp问题?
# 0 1 2 3 4
# [2,3,1,1,4],2
# 用dp[x]表示从x位置起跳,到终点的最短距离
# 那么,dp[x]=min(1+dp[x+1],1+dp[x+2],...,1+dp[x+nums[x])
# 从推导式看,是一个从后往前推的过程,
'''
dp[4]=0
dp[3]=min(1+dp[3+1])=1+dp[4]=1
dp[2]=min(1+dp[2+1])=1+dp[3]=2
dp[1]=min(1+dp[1+1],1+dp[1+2],1+dp[1+3])=min(1+dp[2],1+dp[3],1+dp[4])=min(3,2,1)=1
dp[0]=min(1+dp[0+1],1+dp[0+2])=min(1+dp[1],1+dp[2])=min(2,3)=2
'''
# 注意,题中nums[i]∈[0,1000],可能是0,0这个位置表示跳不动,赋值为INF
inf=float('inf')
'''
简化一下,其实就是:
dp[x] =1+min(dp[x+1:x+nums[x]+1], nums[x]!=0
=inf, nums[x]==0
'''
len=nums.__len__()
dp=[inf]*len
dp[-1]=0
i=len-2
while i>=0:
if nums[i]==0: i-=1;continue
dp[i]=1+min(dp[i+1:i+nums[i]+1])
i-=1
return dp[0]
if __name__ == '__main__':
print(jump([2,3,1,1,4]))
print(jump([2,3,0,1,4]))
print(jump([2]))
print(jump([2,1]))
print(jump([1,1]))
print(jump([1,1,1]))
print(jump([0,1,1]))
print(jump([3,1,1]))

[TODO] 看来有更快的解法!

浙公网安备 33010602011771号