Leetcode 1340. Jump Game V
Posted SnailTyan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1340. Jump Game V相关的知识,希望对你有一定的参考价值。
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
**解析:**Version 1,采用深度优先搜索,使用visited
记录遍历过的索引及对应的跳跃次数,如果当前索引遍历过,直接返回对应的跳跃次数,分别遍历其左右两侧,取左右两侧最大的跳跃次数,返回最大跳跃次数加上当前元素的跳跃次数1
。Version 2对数组先排序,获得排序后的索引,然后从最小值的索引开始寻找左右两侧最大跳跃次数,这样每个数左右两侧比其小的数的跳跃次数都已计算出来,所有元素的初始默认跳跃次数为1
,依次更新dp[current]
,最后返回最大跳跃次数。
- Version 1
class Solution:
def maxJumps(self, arr: List[int], d: int) -> int:
stat = {}
n = len(arr)
visited = {}
nums = 0
for i in range(n):
nums = max(nums, self.dfs(arr, i, visited, d))
return nums
def dfs(self, arr, current, visited, d):
if current in visited:
return visited[current]
n = len(arr)
count = 0
i = current - 1
thres = max(-1, current - d - 1)
while i > thres and arr[i] < arr[current]:
temp = self.dfs(arr, i, visited, d)
visited[i] = temp
count = max(count, temp)
i -= 1
i = current + 1
thres = min(n, current + d + 1)
while i < thres and arr[i] < arr[current]:
temp = self.dfs(arr, i, visited, d)
visited[i] = temp
count = max(count, temp)
i += 1
return count + 1
- Version 2
class Solution:
def maxJumps(self, arr: List[int], d: int) -> int:
indexes = sorted(range(len(arr)), key=lambda i: arr[i])
n = len(arr)
dp = [1] * n
nums = 0
for current in indexes:
i = current - 1
thres = max(-1, current - d - 1)
count = 0
while i > thres and arr[i] < arr[current]:
count = max(count, dp[i])
i -= 1
i = current + 1
thres = min(n, current + d + 1)
while i < thres and arr[i] < arr[current]:
count = max(count, dp[i])
i += 1
dp[current] += count
nums = max(nums, dp[current])
return nums
Reference
以上是关于Leetcode 1340. Jump Game V的主要内容,如果未能解决你的问题,请参考以下文章