Skip to content

Commit 8a07f61

Browse files
committed
贪婪算法
1 parent 15c991d commit 8a07f61

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

greedy/jump.md

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
```python
2+
def canJump(nums):
3+
n = len(nums)
4+
max_reach = 0
5+
6+
for i in range(n):
7+
if i > max_reach:
8+
return False
9+
max_reach = max(max_reach, i + nums[i])
10+
11+
return True
12+
```
13+
14+
1. 首先获取输入数组 `nums` 的长度 `n`
15+
2. 初始化 `max_reach` 变量,用于记录当前可以到达的最远位置。
16+
3. 遍历数组 `nums`,对于每个位置 `i`:
17+
- 如果 `i` 大于当前的 `max_reach`,说明无法到达该位置,返回 `False`
18+
- 更新 `max_reach` 为当前 `max_reach``i + nums[i]` 的最大值。
19+
4. 如果能遍历完整个数组,说明可以到达最后一个位置,返回 `True`
20+
21+
这个解决方案的时间复杂度为 O(n),空间复杂度为 O(1),因为我们只使用了一个额外的变量 `max_reach`
22+
23+
你可以将这个函数用在你的代码中,测试一下它的正确性。如果你有任何其他问题,欢迎随时询问我。

greedy/jump.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
def canJump(nums):
2+
n = len(nums)
3+
max_reach = 0
4+
5+
for i in range(n):
6+
if i > max_reach:
7+
return False
8+
max_reach = max(max_reach, i + nums[i])
9+
10+
return True

src/dp/coin.py

+3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
from typing import List
2+
"""
3+
换钱。
24
5+
"""
36
class Solution:
47
def coinChange(self, coins: List[int], amount: int) -> int:
58
if amount == 0:

0 commit comments

Comments
 (0)