Last active
December 23, 2015 09:09
-
-
Save kijuky/6612172 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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