11"""
22 In this problem, we want to determine all possible combinations of k
33 numbers out of 1 ... n. We use backtracking to solve this problem.
4- Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!)))
4+
5+ Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))),
56"""
67from __future__ import annotations
78
9+ from itertools import combinations
10+
11+
12+ def combination_lists (n : int , k : int ) -> list [list [int ]]:
13+ """
14+ >>> combination_lists(n=4, k=2)
15+ [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
16+ """
17+ return [list (x ) for x in combinations (range (1 , n + 1 ), k )]
18+
819
920def generate_all_combinations (n : int , k : int ) -> list [list [int ]]:
1021 """
1122 >>> generate_all_combinations(n=4, k=2)
1223 [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
24+ >>> generate_all_combinations(n=0, k=0)
25+ [[]]
26+ >>> generate_all_combinations(n=10, k=-1)
27+ Traceback (most recent call last):
28+ ...
29+ RecursionError: maximum recursion depth exceeded
30+ >>> generate_all_combinations(n=-1, k=10)
31+ []
32+ >>> generate_all_combinations(n=5, k=4)
33+ [[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]]
34+ >>> from itertools import combinations
35+ >>> all(generate_all_combinations(n, k) == combination_lists(n, k)
36+ ... for n in range(1, 6) for k in range(1, 6))
37+ True
1338 """
1439
1540 result : list [list [int ]] = []
@@ -34,13 +59,17 @@ def create_all_state(
3459 current_list .pop ()
3560
3661
37- def print_all_state (total_list : list [list [int ]]) -> None :
38- for i in total_list :
39- print (* i )
62+ if __name__ == "__main__" :
63+ from doctest import testmod
4064
65+ testmod ()
66+ print (generate_all_combinations (n = 4 , k = 2 ))
67+ tests = ((n , k ) for n in range (1 , 5 ) for k in range (1 , 5 ))
68+ for n , k in tests :
69+ print (n , k , generate_all_combinations (n , k ) == combination_lists (n , k ))
4170
42- if __name__ == "__main__" :
43- n = 4
44- k = 2
45- total_list = generate_all_combinations ( n , k )
46- print_all_state ( total_list )
71+ print ( "Benchmark:" )
72+ from timeit import timeit
73+
74+ for func in ( "combination_lists" , "generate_all_combinations" ):
75+ print ( f" { func :>25 } (): { timeit ( f' { func } (n=4, k = 2)' , globals = globals ()) } " )
0 commit comments