Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3149
一个人的身影
一个人的身影 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
    2020-11-21 07:17

    Swift 3 conversion of Java solution: (by @JeremyThompson)

    protocol _IntType { }
    extension Int: _IntType {}
    
    
    extension Array where Element: _IntType {
    
        func subsets(to: Int) -> [[Element]]? {
    
            func sum_up_recursive(_ numbers: [Element], _ target: Int, _ partial: [Element], _ solution: inout [[Element]]) {
    
                var sum: Int = 0
                for x in partial {
                    sum += x as! Int
                }
    
                if sum == target {
                    solution.append(partial)
                }
    
                guard sum < target else {
                    return
                }
    
                for i in stride(from: 0, to: numbers.count, by: 1) {
    
                    var remaining = [Element]()
    
                    for j in stride(from: i + 1, to: numbers.count, by: 1) {
                        remaining.append(numbers[j])
                    }
    
                    var partial_rec = [Element](partial)
                    partial_rec.append(numbers[i])
    
                    sum_up_recursive(remaining, target, partial_rec, &solution)
                }
            }
    
            var solutions = [[Element]]()
            sum_up_recursive(self, to, [Element](), &solutions)
    
            return solutions.count > 0 ? solutions : nil
        }
    
    }
    

    usage:

    let numbers = [3, 9, 8, 4, 5, 7, 10]
    
    if let solution = numbers.subsets(to: 15) {
        print(solution) // output: [[3, 8, 4], [3, 5, 7], [8, 7], [5, 10]]
    } else {
        print("not possible")
    }
    

提交回复
热议问题