Finding all possible combinations of numbers to reach a given sum

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

    Here's a solution in R

    subset_sum = function(numbers,target,partial=0){
      if(any(is.na(partial))) return()
      s = sum(partial)
      if(s == target) print(sprintf("sum(%s)=%s",paste(partial[-1],collapse="+"),target))
      if(s > target) return()
      for( i in seq_along(numbers)){
        n = numbers[i]
        remaining = numbers[(i+1):length(numbers)]
        subset_sum(remaining,target,c(partial,n))
      }
    }
    

提交回复
热议问题