1
+ from typing import Any , List
2
+
3
+
4
+ # Base Case:
5
+
6
+ # If k equals n, it means we have considered all elements, and we process the current subset.
7
+ # Recursive Case:
8
+
9
+ # The function search(k + 1) is called without including the current element k in the subset.
10
+ # The element k is then added to the subset, and search(k + 1) is called again to include the current element in the subset.
11
+ # After processing the subset including the current element, it is removed (subset.pop_back()) to backtrack.
12
+
13
+ # void search(int k) {
14
+ # if (k == n) {
15
+ # // process subset
16
+ # } else {
17
+ # search(k + 1);
18
+ # subset.push_back(k);
19
+ # search(k + 1);
20
+ # subset.pop_back();
21
+ # }
22
+ # }
23
+
24
+ def search (k : int , n : int , subset : list [Any ], all_subsets : list [list [Any ]]):
25
+ """
26
+ :param k: current index
27
+ :param n: length of nums
28
+ :param subset: current subset
29
+ :param all_subsets: all subsets
30
+
31
+ When the function search is called with parameter k, it decides whether to
32
+ include the element k in the subset or not, and in both cases, then calls itself
33
+ with parameter k + 1 However, if k = n, the function notices that all elements
34
+ have been processed and a subset has been generated.
35
+ The following tree illustrates the function calls when n = 3. We can always
36
+ choose either the left branch (k is not included in the subset) or the right branch
37
+ (k is included in the subset).
38
+ """
39
+ if k == n :
40
+ # process subset
41
+ all_subsets .append (subset [:])
42
+ else :
43
+ # The function search(k + 1) is called without including the current element k in the subset.
44
+ search (k + 1 , n , subset , all_subsets )
45
+ # Include nums[k] in the subset
46
+ # The element k is then added to the subset, and search(k + 1) is called again to include the current element in the subset.
47
+ subset .append (k )
48
+ search (k + 1 , n , subset , all_subsets )
49
+
50
+ subset .pop ()
51
+
52
+ def subsets_recursive (nums : List [int ]) -> List [List [int ]]:
53
+ all_subsets = []
54
+ search (0 , len (nums ), [], all_subsets )
55
+ return all_subsets
56
+
57
+
58
+ print (subsets_recursive ([1 , 2 , 3 ])) # Output: [[], [2], [1], [1, 2], [3], [2, 3], [1, 3], [1, 2, 3]]
59
+
60
+
61
+
62
+ # def subsets(nums: List[int]) -> List[List[int]]:
63
+ # result: List[List[int]] = [[]]
64
+ # for num in nums:
65
+ # result += [curr + [num] for curr in result]
66
+ # return result
67
+
68
+
69
+ # def subsets_bitmask(nums: List[int]) -> List[List[int]]:
70
+ # n = len(nums)
71
+ # result = []
72
+ # for i in range(1 << n):
73
+ # subset = []
74
+ # for j in range(n):
75
+ # if i & (1 << j):
76
+ # subset.append(nums[j])
77
+ # result.append(subset)
78
+ # return result
0 commit comments