1. 程式人生 > >c# C(m,n) 排列組合演算法

c# C(m,n) 排列組合演算法

n從1到m的所有組合:

static void Main()
{
    string[] arr = new string[] { "a", "b", "c", "d", "e" };
    List<string[]> list = new List<string[]>();
    foreach (string s in arr)
    {
        List<string[]> lst = list.GetRange(0, list.Count);
        string[] nArr = { s };
        list.Add(nArr);
        foreach (string[] ss in lst)
        {
            list.Add(ss.Concat(nArr).ToArray());
        }
    }
    List<string[]> outList = list.OrderByDescending(p => p.Length).ToList();
    outList.ForEach(p => Console.WriteLine(string.Join(",", p)));
}

n以內的所有組合:

static void Main()
{
    string[] arr = new string[] { "a", "b", "c", "d", "e" };
    int n = 2;//長度為2以內的所有組合
    List<string[]> list = new List<string[]>();
    foreach (string s in arr)
    {
        List<string[]> lst = list.Where(p => p.Length < n).ToList();
        string[] nArr = { s };
        list.Add(nArr);
        foreach (string[] ss in lst)
        {
            list.Add(ss.Concat(nArr).ToArray());
        }
    }
    List<string[]> outList = list.OrderByDescending(p => p.Length).ToList();
    outList.ForEach(p => Console.WriteLine(string.Join(",", p)));
}