leetcode45.跳跃游戏 II

45. 跳跃游戏 II

中等(跳跃游戏)

给定一个长度为 n0 索引整数数组 nums。初始位置为 nums[0]

每个元素 nums[i] 表示从索引 i 向后跳转的最大长度。换句话说,如果你在 nums[i] 处,你可以跳转到任意 nums[i + j] 处:

  • 0 <= j <= nums[i]
  • i + j < n

返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]

示例 1:

输入: nums = [2,3,1,1,4]
输出: 2
解释: 跳到最后一个位置的最小跳跃数是 2。
从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。

示例 2:

输入: nums = [2,3,0,1,4]
输出: 2

代码一:递归

执行用时分布 4848ms 击败8.53%

消耗内存分布 30.47MB 击败5.03%

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
@cache
def func1(pos):
if pos == n-1:
return 0
k = nums[pos]
if k + pos >= n-1:
return 1
ans = +inf
for i in range(pos+1,k+pos+1):
ans = min(ans,1+func1(i))
return ans
return func1(0)

思路:

递归算法,如果遍历到最后一个元素,返回0;如果下一次能到达最后一个元素,返回1。依次遍历此次所能到达的最远距离,返回能到达最后元素的最少次数。

代码二:一次遍历

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def jump(self, nums: List[int]) -> int:
ans = 0
cur_right = 0 # 已建造的桥的右端点
next_right = 0 # 下一座桥的右端点的最大值
for i in range(len(nums) - 1):
next_right = max(next_right, i + nums[i])
if i == cur_right: # 到达已建造的桥的右端点
cur_right = next_right # 造一座桥
ans += 1
return ans

思路:

45-c.png