博客园  :: 首页  :: 联系 :: 订阅 订阅  :: 管理

对List内元素进行全排列

Posted on 2009-11-16 20:49  生鱼片  阅读(689)  评论(3编辑  收藏  举报

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);

                }

            }

        }      

}

结果如下:

clip_image002