|
1 | 1 | ''' |
2 | | -The power set |
| 2 | +The Power Set |
3 | 3 |
|
4 | 4 | The power set of a set is the set of all its subsets. |
5 | 5 | Write a function that, given a set, generates its power set. |
6 | 6 |
|
7 | | -Input: {1, 2, 3} |
8 | | -Output: {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}} |
| 7 | +Input: [1, 2, 3] |
| 8 | +Output: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] |
9 | 9 | * You may also use a list or array to represent a set. |
10 | 10 |
|
11 | 11 | ========================================= |
12 | 12 | Simple recursive combinations algorithm. |
13 | 13 | Time Complexity: O(Sum(C(I, N))) , sum of all combinations between 0 and N = C(0, N) + C(1, N) + ... + C(N, N) |
14 | | - Space Complexity: O(Sum(C(I, N))) , this is for the result array, if we print the number then the space complexity will be O(1) |
| 14 | + Space Complexity: O(Sum(C(I, N))) , this is for the result array, if we print the number then the space complexity will be O(N) (because of the recursive stack) |
15 | 15 | ''' |
16 | 16 |
|
17 | 17 |
|
|
20 | 20 | ############ |
21 | 21 |
|
22 | 22 | def power_set(arr): |
23 | | - return combinations(arr, [], 0) |
24 | | - |
25 | | -# arr and taken are the same pointer always |
26 | | -# the same arrays are used always |
27 | | -def combinations(arr, taken, pos): |
28 | 23 | result = [] |
29 | | - result.append([arr[i] for i in taken]) # create the current combination |
| 24 | + combinations(result, arr, [], 0) |
| 25 | + return result |
30 | 26 |
|
31 | | - if len(arr) == pos: |
32 | | - return result |
| 27 | +# result, arr and taken are the same references always |
| 28 | +def combinations(result, arr, taken, pos): |
| 29 | + result.append([arr[i] for i in taken]) # create the current combination |
33 | 30 |
|
34 | 31 | n = len(arr) |
| 32 | + if n == pos: |
| 33 | + return |
| 34 | + |
35 | 35 | # start from the last position (don't need duplicates) |
36 | 36 | for i in range(pos, n): |
37 | 37 | taken.append(i) |
38 | | - result += combinations(arr, taken, i + 1) # append the combinations |
| 38 | + combinations(result, arr, taken, i + 1) |
39 | 39 | del taken[-1] # return to the old state |
40 | 40 |
|
41 | | - return result |
42 | | - |
43 | 41 |
|
44 | 42 | ########### |
45 | 43 | # Testing # |
|
0 commit comments