Skip to content

Commit 3bbd4f5

Browse files
authored
Create 77_Combinations.md
1 parent 00673fe commit 3bbd4f5

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

77_Combinations.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
## 77. Combinations
2+
3+
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
4+
5+
You may return the answer in any order.
6+
7+
8+
9+
Example 1:
10+
11+
Input: n = 4, k = 2
12+
Output:
13+
[
14+
[2,4],
15+
[3,4],
16+
[2,3],
17+
[1,2],
18+
[1,3],
19+
[1,4],
20+
]
21+
Example 2:
22+
23+
Input: n = 1, k = 1
24+
Output: [[1]]
25+
26+
27+
Constraints:
28+
29+
1 <= n <= 20
30+
1 <= k <= n
31+
32+
```python
33+
def combine(self, n: int, k: int) -> List[List[int]]:
34+
def gen_pattern(nums, k):
35+
if k == 0:
36+
return [[]]
37+
if k == 1:
38+
return [[num] for num in nums]
39+
40+
res = []
41+
for i in range(len(nums)):
42+
perms = gen_pattern(nums[i+1:], k-1)
43+
for p in perms:
44+
res.append([nums[i]] + p)
45+
return res
46+
47+
nums = list(range(1, n+1))
48+
res = gen_pattern(nums, k)
49+
return res
50+
```
51+
52+
53+
```
54+
Runtime: 556 ms, faster than 37.57% of Python3 online submissions for Combinations.
55+
Memory Usage: 16.2 MB, less than 33.85% of Python3 online submissions for Combinations.
56+
```

0 commit comments

Comments
 (0)