日期:2014-05-17  浏览次数:20814 次

排列组合算法怎样写
请问排列组合的算法怎样写?
比如有"A","B","C",排列组合成六种可能的结果:
"A","B","C" ; "A","C","B"
"B","A","C" ; "B","C","A"
"C","A","B" ; "C","B","A"
以后会有"A","B","C","D"
请问程序怎样写可以得出这些结果,谢谢!

------解决方案--------------------
这叫做全排列。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "ABCD";
            List<string> list = new List<string>();
            foreach (var i in Combo(s, 4))
            {
                list = list.Union(Arrange(i)).ToList();
            }
            list.ForEach(x => Console.WriteLine(x));
        }


        static IEnumerable<string> Arrange(string source)
        {
            for (int i = 0; i < source.Length; i++)
            {
                if (source.Length == 1)
                {
                    yield return source;
                }
                else
                {
                    foreach (var x in Arrange(source.Substring(0, i) + source.Substring(i + 1)))
                    {
                        yield return source[i] + x;
                    }
                }
            }
        }

        static IEnumerable<string> Combo(string source, int len)
     &