Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3234
一个人的身影
一个人的身影 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 07:02

    Recommended as an answer:

    Here's a solution using es2015 generators:

    function* subsetSum(numbers, target, partial = [], partialSum = 0) {
    
      if(partialSum === target) yield partial
    
      if(partialSum >= target) return
    
      for(let i = 0; i < numbers.length; i++){
        const remaining = numbers.slice(i + 1)
            , n = numbers[i]
    
        yield* subsetSum(remaining, target, [...partial, n], partialSum + n)
      }
    
    }
    

    Using generators can actually be very useful because it allows you to pause script execution immediately upon finding a valid subset. This is in contrast to solutions without generators (ie lacking state) which have to iterate through every single subset of numbers

提交回复
热议问题