-
Notifications
You must be signed in to change notification settings - Fork 292
/
Subset.cs
38 lines (29 loc) · 900 Bytes
/
Subset.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System.Collections.Generic;
namespace Advanced.Algorithms.Combinatorics;
/// <summary>
/// Subset generator.
/// </summary>
public class Subset
{
public static List<List<T>> Find<T>(List<T> input)
{
var result = new List<List<T>>();
Recurse(input, 0, new List<T>(), new HashSet<int>(), result);
return result;
}
private static void Recurse<T>(List<T> input,
int k, List<T> prefix, HashSet<int> prefixIndices,
List<List<T>> result)
{
result.Add(new List<T>(prefix));
for (var j = k; j < input.Count; j++)
{
if (prefixIndices.Contains(j)) continue;
prefix.Add(input[j]);
prefixIndices.Add(j);
Recurse(input, j + 1, prefix, prefixIndices, result);
prefix.RemoveAt(prefix.Count - 1);
prefixIndices.Remove(j);
}
}
}