Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3089
一个人的身影
一个人的身影 2020-11-21 06:39

How would you go about testing all possible combinations of additions from a given set N of numbers so they add up to a given final number?

A brief exam

30条回答
  •  时光说笑
    2020-11-21 06:57

    In Haskell:

    filter ((==) 12345 . sum) $ subsequences [1,5,22,15,0,..]
    

    And J:

    (]#~12345=+/@>)(]<@#~[:#:@i.2^#)1 5 22 15 0 ...
    

    As you may notice, both take the same approach and divide the problem into two parts: generate each member of the power set, and check each member's sum to the target.

    There are other solutions but this is the most straightforward.

    Do you need help with either one, or finding a different approach?

提交回复
热议问题