-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathPermutation.cs
42 lines (33 loc) · 1.05 KB
/
Permutation.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
39
40
41
42
using System.Collections.Generic;
namespace Advanced.Algorithms.Combinatorics;
/// <summary>
/// Permutation generator (nPr).
/// </summary>
public class Permutation
{
public static List<List<T>> Find<T>(List<T> n, int r, bool withRepetition = false)
{
var result = new List<List<T>>();
Recurse(n, r, withRepetition, new List<T>(), new HashSet<int>(), result);
return result;
}
private static void Recurse<T>(List<T> n, int r, bool withRepetition,
List<T> prefix, HashSet<int> prefixIndices,
List<List<T>> result)
{
if (prefix.Count == r)
{
result.Add(new List<T>(prefix));
return;
}
for (var j = 0; j < n.Count; j++)
{
if (prefixIndices.Contains(j) && !withRepetition) continue;
prefix.Add(n[j]);
prefixIndices.Add(j);
Recurse(n, r, withRepetition, prefix, prefixIndices, result);
prefix.RemoveAt(prefix.Count - 1);
prefixIndices.Remove(j);
}
}
}