Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3144
一个人的身影
一个人的身影 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 07:00

    I was doing something similar for a scala assignment. Thought of posting my solution here:

     def countChange(money: Int, coins: List[Int]): Int = {
          def getCount(money: Int, remainingCoins: List[Int]): Int = {
            if(money == 0 ) 1
            else if(money < 0 || remainingCoins.isEmpty) 0
            else
              getCount(money, remainingCoins.tail) +
                getCount(money - remainingCoins.head, remainingCoins)
          }
          if(money == 0 || coins.isEmpty) 0
          else getCount(money, coins)
        }
    

提交回复
热议问题