Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3147
一个人的身影
一个人的身影 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条回答
  •  Happy的楠姐
    2020-11-21 07:06

    I thought I'd use an answer from this question but I couldn't, so here is my answer. It is using a modified version of an answer in Structure and Interpretation of Computer Programs. I think this is a better recursive solution and should please the purists more.

    My answer is in Scala (and apologies if my Scala sucks, I've just started learning it). The findSumCombinations craziness is to sort and unique the original list for the recursion to prevent dupes.

    def findSumCombinations(target: Int, numbers: List[Int]): Int = {
      cc(target, numbers.distinct.sortWith(_ < _), List())
    }
    
    def cc(target: Int, numbers: List[Int], solution: List[Int]): Int = {
      if (target == 0) {println(solution); 1 }
      else if (target < 0 || numbers.length == 0) 0
      else 
        cc(target, numbers.tail, solution) 
        + cc(target - numbers.head, numbers, numbers.head :: solution)
    }
    

    To use it:

     > findSumCombinations(12345, List(1,5,22,15,0,..))
     * Prints a whole heap of lists that will sum to the target *
    

提交回复
热议问题