40
1
using System;
2
3
var input = new int[] { 3, 4, 1, 5, 2, 7, 4, 2, 6 };
4
5
var numberOfSubsets = (int)Math.Pow(2, input.Length);
6
7
var subsets = new int[numberOfSubsets][];
8
9
int nextEmptyIndex = 0;
10
11
// Add the empty set
12
subsets[nextEmptyIndex++] = new int[0];
13
14
foreach (int element in input)
15
{
16
// Record the index of the end of the current elements.
17
int stopIndex = nextEmptyIndex - 1;
18
19
20
// Add the subsets of the previously existing elements
21
// and the new element. Skip the empty set at index 0.
22
for (int i = 0; i <= stopIndex; i++)
23
{
24
int newSubsetLength = subsets[i].Length + 1;
25
int newSubsetIndex = nextEmptyIndex++;
26
27
subsets[newSubsetIndex] = new int[newSubsetLength];
28
29
Array.Copy(subsets[i], subsets[newSubsetIndex], subsets[i].Length);
30
31
subsets[newSubsetIndex][newSubsetLength - 1] = element;
32
}
33
}
34
35
for (int i = 0; i < subsets.Length; i++)
36
{
37
Console.WriteLine($"subsets[{ i }] = { string.Join(", ", subsets[i]) }");
38
}
39
40
Cached Result