Leetcode 1340. Jump Game V

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Jump Game V

2. Solution

解析:Version 1,采用深度优先搜索,使用visited记录遍历过的索引及对应的跳跃次数,如果当前索引遍历过,直接返回对应的跳跃次数,分别遍历其左右两侧,取左右两侧最大的跳跃次数,返回最大跳跃次数加上当前元素的跳跃次数1。Version 2对数组先排序,获得排序后的索引,然后从最小值的索引开始寻找左右两侧最大跳跃次数,这样每个数左右两侧比其小的数的跳跃次数都已计算出来,所有元素的初始默认跳跃次数为1,依次更新dp[current],最后返回最大跳跃次数。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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

  1. https://leetcode.com/problems/jump-game-v/
如果有收获,可以请我喝杯咖啡!