-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path77_combinations.py
41 lines (32 loc) · 1.06 KB
/
77_combinations.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from typing import List
class Solution:
def combine0(self, n: int, k: int) -> List[List[int]]:
def dfs(start: int, option: List[int]):
for i in range(start, n + 1 - (k - 1 - len(option))):
option.append(i)
if len(option) == k:
ans.append(option[:])
else:
dfs(i + 1, option)
option.pop()
ans = []
dfs(1, [])
return ans
def combine(self, n: int, k: int) -> List[List[int]]:
def dfs(start: int, idx: int):
for i in range(start, n + 1 - (k - 1 - idx)):
option[idx] = i
if idx == k - 1:
ans.append(option[:])
else:
dfs(i + 1, idx + 1)
ans = []
option = [0] * k
dfs(1, 0)
return ans
def test():
ans = Solution().combine(5, 4)
expect = [[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]]
assert ans == expect, ans
if __name__ == "__main__":
test()