對List中元素進行全排列,使用了遞歸,代碼如下:
class Program { static void Main(string[] args) { List<int> list = new List<int>() { 6,7,8}; foreach (var p1 in Permutate(list, list.Count)) { foreach (var i in p1) Console.Write(i.ToString() + " "); Console.WriteLine(); } string strTest = "Cary"; foreach (List<char> p2 in Permutate(strTest.ToCharArray().ToList(), strTest.Length)) { string strTmp = new string(p2.ToArray()); Console.Write(strTmp + " "); } Console.WriteLine(); } public static void CircleRight(IList seq, int count) { object tmp = seq[count - 1]; seq.RemoveAt(count - 1); seq.Insert(0, tmp); } public static IEnumerable<IList> Permutate(IList seq, int count) { if (count == 1) yield return seq; else { for (int i = 0; i < count; i++) { foreach (var perm in Permutate(seq, count - 1)) yield return perm; CircleRight(seq, count); } }