Skip to content

Commit 628794d

Browse files
obelisk0114cclauss
authored andcommitted
Add combinations (TheAlgorithms#1015)
* Update Bucket Sort time complexity analysis * Add combinations * Adding doctest * Fix doctest problem
1 parent 0d61539 commit 628794d

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

backtracking/all_combinations.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# -*- coding: utf-8 -*-
2+
3+
"""
4+
In this problem, we want to determine all possible combinations of k
5+
numbers out of 1 ... n. We use backtracking to solve this problem.
6+
Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!)))
7+
"""
8+
9+
10+
def generate_all_combinations(n: int, k: int) -> [[int]]:
11+
"""
12+
>>> generate_all_combinations(n=4, k=2)
13+
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
14+
"""
15+
16+
result = []
17+
create_all_state(1, n, k, [], result)
18+
return result
19+
20+
21+
def create_all_state(increment, total_number, level, current_list, total_list):
22+
if level == 0:
23+
total_list.append(current_list[:])
24+
return
25+
26+
for i in range(increment, total_number - level + 2):
27+
current_list.append(i)
28+
create_all_state(i + 1, total_number, level - 1, current_list, total_list)
29+
current_list.pop()
30+
31+
32+
def print_all_state(total_list):
33+
for i in total_list:
34+
print(*i)
35+
36+
37+
if __name__ == '__main__':
38+
n = 4
39+
k = 2
40+
total_list = generate_all_combinations(n, k)
41+
print_all_state(total_list)

0 commit comments

Comments
 (0)