algorithm to sum up a list of numbers for all combinations

前端 未结 15 2285
北荒
北荒 2020-12-04 22:34

I have a list of numbers and I want to add up all the different combinations. For example:

  • number as 1,4,7 and 13
  • the output would be:

15条回答
  •  盖世英雄少女心
    2020-12-04 23:08

    This is not the code to generate the sums, but it generates the permutations. In your case:

    1; 1,4; 1,7; 4,7; 1,4,7; ...

    If I have a moment over the weekend, and if it's interesting, I can modify this to come up with the sums.

    It's just a fun chunk of LINQ code from Igor Ostrovsky's blog titled "7 tricks to simplify your programs with LINQ" (http://igoro.com/archive/7-tricks-to-simplify-your-programs-with-linq/).

    T[] arr = …;
    var subsets = from m in Enumerable.Range(0, 1 << arr.Length)
                  select
                      from i in Enumerable.Range(0, arr.Length)
                      where (m & (1 << i)) != 0
                      select arr[i];
    

提交回复
热议问题