algorithm to sum up a list of numbers for all combinations

前端 未结 15 2270
北荒
北荒 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:17

    You can enumerate all subsets using a bitvector.

    In a for loop, go from 0 to 2 to the Nth power minus 1 (or start with 1 if you don't care about the empty set).

    On each iteration, determine which bits are set. The Nth bit represents the Nth element of the set. For each set bit, dereference the appropriate element of the set and add to an accumulated value.

    ETA: Because the nature of this problem involves exponential complexity, there's a practical limit to size of the set you can enumerate on. If it turns out you don't need all subsets, you can look up "n choose k" for ways of enumerating subsets of k elements.

提交回复
热议问题