Words combinations without repetition

后端 未结 4 690
栀梦
栀梦 2020-12-03 18:58

I have 10 words. How can I get all possible combinations of 5 words (n=10, k=5). The order does not matter.

For example: \"A\",

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 19:11

    public IActionResult Index() 
    {
        var list = new List { "a", "b", "c", "d", "e" };
        List ret = GetAllCombinations(list).OrderBy(_ => _).ToList();
    
        return View();
    }
    
    static IEnumerable GetAllCombinations(IEnumerable list)
    {
        return list.SelectMany((mainItem, mi) => list.Where((otherItem, oi) => mi < oi)
                                  .Select(otherItem => mainItem + otherItem));
    }
    

    Ouput ret:

    ab
    ac
    ad
    ae
    bc
    bd
    be
    cd
    ce
    de
    

提交回复
热议问题