Skip to content

Instantly share code, notes, and snippets.

@kijuky
Last active December 23, 2015 09:09
Show Gist options
  • Save kijuky/6612172 to your computer and use it in GitHub Desktop.
Save kijuky/6612172 to your computer and use it in GitHub Desktop.
// yield 版
IEnumerable<List<T>> Permutations<T>(IEnumerable<T> seq, int count)
{
switch (count) {
case 0: // special
yield break;
case 1: // terminate
foreach (var t in seq)
yield return t;
yield break;
default: // permutation
var list = seq.ToList(); // defensive copy
foreach (var head in list)
foreach (var tail in Permutations(list.Skip(1), count - 1))
yield return new List<T>{ head }.Concat(tail).ToList();
yield break;
}
}
// LINQ版
IEnumerable<List<T>> Permutations<T>(IEnumerable<T> seq, int count)
{
switch (count) {
case 0: // special
return Enumerable.Empty<List<T>>();
case 1: // terminate
return from t in seq
select new List<T>{ t };
default: // permutation
var list = seq.ToList(); // defensive copy
return from head in list
from tail in Permutations(list.Skip(1), count - 1)
select new List<T>{ head }.Concat(tail).ToList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment