1
+
2
+
3
+ /**
4
+ * Return an array of arrays of size *returnSize.
5
+ * The sizes of the arrays are returned as *returnColumnSizes array.
6
+ * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
7
+ */
8
+
9
+ int nCr (int * factorials , int n , int r ) {
10
+ return (int )(factorials [n ] / (factorials [r ] * (factorials [n - r ])));
11
+ }
12
+
13
+ int * * subsets (int * nums , int numsSize , int * returnSize , int * * returnColumnSizes ){
14
+
15
+ int * factorials = (int * )malloc ((numsSize + 1 ) * sizeof (int ));
16
+ factorials [0 ] = 1 ;
17
+ factorials [1 ] = 1 ;
18
+
19
+ for (int i = 2 ; i < (numsSize + 1 ); i ++ ) {
20
+ factorials [i ] = factorials [i - 1 ] * i ;
21
+ }
22
+
23
+ int combinations = 0 ;
24
+ for (int i = 0 ; i < (numsSize + 1 ); i ++ ) {
25
+ combinations += nCr (factorials , numsSize , i );
26
+ }
27
+ * returnSize = combinations ;
28
+
29
+ int * * result = (int * * )malloc (combinations * sizeof (int * ));
30
+ returnColumnSizes [0 ] = (int * )malloc (combinations * sizeof (int ));
31
+ returnColumnSizes [0 ][0 ] = 0 ;
32
+
33
+ int current_size = 1 ;
34
+ int lead = 1 ;
35
+ for (int i = 0 ; i < numsSize ; i ++ ) {
36
+ for (int j = 0 ; j < current_size ; j ++ ) {
37
+ int * new_subset = (int * )malloc ((returnColumnSizes [0 ][j ] + 1 ) * sizeof (int ));
38
+ for (int k = 0 ; k < returnColumnSizes [0 ][j ]; k ++ ) {
39
+ new_subset [k ] = result [j ][k ];
40
+ }
41
+ new_subset [returnColumnSizes [0 ][j ]] = nums [i ];
42
+ result [lead ] = new_subset ;
43
+ returnColumnSizes [0 ][lead ] = (returnColumnSizes [0 ][j ] + 1 );
44
+ lead += 1 ;
45
+ }
46
+ current_size = lead ;
47
+ }
48
+ free (factorials );
49
+ return result ;
50
+ }
0 commit comments