Skip to content

Commit 125aa21

Browse files
author
devin
committed
feat: 第 45 题添加新思路
1 parent da59332 commit 125aa21

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

docs/Leetcode_Solutions/Python/0045._Jump_Game_II.md

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ You can assume that you can always reach the last index.
3838
递归, 超时
3939

4040

41-
```
41+
```python
4242
class Solution:
4343
def jump(self, nums):
4444
"""
@@ -67,7 +67,7 @@ DP
6767

6868
dp[i]代表的是到达index为idx的位置的最少步数, 依然超时,最后2个case过不了
6969

70-
```
70+
```python
7171
class Solution:
7272
def jump(self, nums):
7373
"""
@@ -120,3 +120,27 @@ class Solution:
120120
```
121121

122122

123+
> 思路 4
124+
125+
要想获得最小跳跃次数,每次在可跳范围内选择势能最高的点,即下次能跳得最远的点,是:num[i]+i最大值,而不是 num[i]
126+
127+
```python
128+
class Solution:
129+
def jump(self, nums: List[int]) -> int:
130+
if len(nums) == 1: # 只有一个元素的情况,直接返回 0
131+
return 0
132+
step = 1
133+
i = 0
134+
while i < len(nums)-1:
135+
if i + nums[i] >= len(nums)-1: # 当前可达,直接返回
136+
return step
137+
else:
138+
max_num = nums[i+1]+i
139+
max_j = i+1
140+
for j in range(i+1, i+nums[i]+1): # 在可跳范围内找下次能跳最远的点
141+
if nums[j]+j >= max_num:
142+
max_num = nums[j]+j
143+
max_j = j
144+
step += 1
145+
i = max_j
146+
```

0 commit comments

Comments
 (0)