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



©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页