Skip to content

Commit 2ff1ec2

Browse files
committed
feat: combinations
1 parent d71a9db commit 2ff1ec2

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

recs.combinations.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""
6+
77. 组合
7+
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
8+
https://leetcode-cn.com/problems/combinations/
9+
"""
10+
# 递归
11+
def combine(self, n: int, k: int) -> List[List[int]]:
12+
res = []
13+
14+
if n == 0 or k == 0:
15+
return res
16+
17+
nums = range(1, n + 1)
18+
19+
def backtrace(rest, curr_res, index):
20+
if len(curr_res) == k:
21+
res.append(curr_res[:])
22+
return
23+
24+
for i in range(index, n):
25+
# 模拟栈,先选一个数
26+
curr_res.append(nums[i])
27+
backtrace(rest[index:], curr_res, i + 1)
28+
# 执行完成后,推出这个数
29+
curr_res.pop()
30+
31+
backtrace(nums, [], 0)
32+
return res
33+
34+
35+
36+
so = Solution()
37+
print(so.combine(3, 2))

0 commit comments

Comments
 (0)