2019-07-14 05:45:54 +00:00
|
|
|
"""
|
2019-11-16 07:05:00 +00:00
|
|
|
In this problem, we want to determine all possible combinations of k
|
|
|
|
numbers out of 1 ... n. We use backtracking to solve this problem.
|
|
|
|
Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!)))
|
2019-07-14 05:45:54 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
def generate_all_combinations(n: int, k: int) -> [[int]]:
|
|
|
|
"""
|
|
|
|
>>> generate_all_combinations(n=4, k=2)
|
|
|
|
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
|
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2019-07-14 05:45:54 +00:00
|
|
|
result = []
|
|
|
|
create_all_state(1, n, k, [], result)
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
2020-11-29 16:19:50 +00:00
|
|
|
def create_all_state(
|
|
|
|
increment: int,
|
|
|
|
total_number: int,
|
|
|
|
level: int,
|
|
|
|
current_list: [int],
|
|
|
|
total_list: [int],
|
|
|
|
) -> None:
|
2019-07-14 05:45:54 +00:00
|
|
|
if level == 0:
|
|
|
|
total_list.append(current_list[:])
|
|
|
|
return
|
|
|
|
|
|
|
|
for i in range(increment, total_number - level + 2):
|
|
|
|
current_list.append(i)
|
|
|
|
create_all_state(i + 1, total_number, level - 1, current_list, total_list)
|
|
|
|
current_list.pop()
|
|
|
|
|
|
|
|
|
2020-11-29 16:19:50 +00:00
|
|
|
def print_all_state(total_list: [int]) -> None:
|
2019-07-14 05:45:54 +00:00
|
|
|
for i in total_list:
|
|
|
|
print(*i)
|
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2019-07-14 05:45:54 +00:00
|
|
|
n = 4
|
|
|
|
k = 2
|
|
|
|
total_list = generate_all_combinations(n, k)
|
|
|
|
print_all_state(total_list)
|