Getting all possible combinations from a list of numbers

前端 未结 3 2076
醉话见心
醉话见心 2020-11-27 18:43

I\'m looking for an efficient way to achieve this:

  • you have a list of numbers 1.....n (typically: 1..5 or 1..7 or so - reasonably small, but can vary from c

3条回答
  •  难免孤独
    2020-11-27 19:01

    Not my code, but you're looking for the powerset. Google gave me this solution, which seems t work:

    public IEnumerable> GetPowerSet(List list)
    {
        return from m in Enumerable.Range(0, 1 << list.Count)
                  select
                      from i in Enumerable.Range(0, list.Count)
                      where (m & (1 << i)) != 0
                      select list[i];
    }
    

    Source: http://rosettacode.org/wiki/Power_set#C.23

提交回复
热议问题