对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 + "\t");
}
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);
}
}
}
}
结果如下:
本文转自生鱼片博客园博客,原文链接:http://www.cnblogs.com/carysun/archive/2009/11/16/List-Permutate.html,如需转载请自行联系原作者