-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathsolution.py
More file actions
20 lines (17 loc) · 625 Bytes
/
Copy pathsolution.py
File metadata and controls
20 lines (17 loc) · 625 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
# Time: O(C(n,k) * k)
# Space: O(C(n,k) * k)
def combine(self, n: int, k: int) -> list[list[int]]:
result: list[list[int]] = []
current: list[int] = []
def backtrack(start: int) -> None:
if len(current) == k:
result.append(current[:])
return
# Prune: stop early if not enough remaining numbers to reach k
for num in range(start, n - (k - len(current)) + 2):
current.append(num)
backtrack(num + 1)
current.pop()
backtrack(1)
return result