Subset sum Swift

可紊 提交于 2019-12-11 13:48:31

问题


I want to use dynamic programming to get the sum of all subsets from a given array.

subsets([1,2,3]) = 24
Since the subsets are {1}{2}{3}{1,2}{2,3}{1,3}{1,2,3}

I'm trying to calculate subsets([1,2]) which = 6 My implementation below gets 5

func subsets(_ arr: [Int]) -> Int {
    var mem = Array(repeating: 0, count: arr.count)
    return subsetsRecursive(arr, 0, &mem)
}

// correct result, but too slow so requires memorization
func subsetsRecursive(_ arr: [Int], _ ptr: Int, _ memo : inout [Int]) -> Int {
    if (ptr > arr.count - 1) {return 0}
    if memo[ptr] != 0 {return memo[ptr]}
    // either take the next number, or don't
    let res = (
        subsetsRecursive(arr, ptr + 1, &memo) + arr[ptr]
            +
        subsetsRecursive(arr, ptr + 1, &memo)
    )
    memo[ptr] = res
    return res
}

What needs to be corrected to get the right answers? The approach here is important, it is not homework but is my self-study about dynamic programming (I can find other approaches for this, but want to understand this approach or why it is not possible).


回答1:


The problem with your approach is that the recursion step does not take into account with how many subsets the current element arr[ptr] can be combined. For example, subsets([1,2]) computes the sum of the subsets {1, 2} and {2}, but omits the subset {1}.

A possible fix for the dynamic programming approach would be to remember not only the sum, but also the count of all subsets starting at a certain position:

func subsets(_ arr: [Int]) -> Int {
    var mem = Array(repeating: (sum: 0, count: 0), count: arr.count)
    return subsetsRecursive(arr, 0, &mem).sum
}

func subsetsRecursive(_ arr: [Int], _ ptr: Int, _ memo : inout [(sum: Int, count: Int)]) -> (sum: Int, count: Int) {
    if (ptr > arr.count - 1) { return (sum: 0, count: 1) }
    if memo[ptr].sum != 0 { return memo[ptr] }
    let res = subsetsRecursive(arr, ptr + 1, &memo)
    memo[ptr] = (2 * res.sum + arr[ptr] * res.count, 2 * res.count)
    return memo[ptr]
}

Examples:

print(subsets([1, 2])) // 6
print(subsets([1, 2, 3])) // 24

This can be simplified further, but hopefully answers your immediate question.


An iterative solution would be

func subsetsum(_ arr: [Int]) -> Int {
    var sum = 0
    var count = 1
    for elem in arr {
        sum = 2 * sum + count * elem
        count = 2 * count
    }
    return sum
}

which can be written concisely as

func subsetsum(_ arr: [Int]) -> Int {
    return arr.reduce((sum: 0, count: 1)) {
        (2 * $0.sum + $0.count * $1, 2 * $0.count )
    }.sum
}

Alternatively note that each of the n array elements can be in 2n-1 of the 2n subsets:

func subsetsum(_ arr: [Int]) -> Int {
    return arr.reduce(0, +) * (1 << (arr.count - 1))
}



回答2:


You can first get all subset elements, join them and use reduce to sum the elements:

extension RangeReplaceableCollection  {
    public var subSets: [SubSequence] {
        return isEmpty ? [SubSequence()] : dropFirst().subSets.lazy.flatMap { [$0, prefix(1) + $0] }
    }
}

let subSets = [1,2,3].subSets // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

let sum = subSets.joined().reduce(0,+)   // 24

or

let sum = subSets.reduce(0) { $1.reduce($0,+) }

Note that extending RangePlaceableCollection and returning a SubSequence you will be able to use it also with StringProtocol types like Strings and Substrings:

let characters = Array("123")
let charactersSubSets = characters.subSets // [[], ["1"], ["2"], ["1", "2"], ["3"], ["1", "3"], ["2", "3"], ["1", "2", "3"]]
let stringSubSets = "123".subSets // ["", "1", "2", "12", "3", "13", "23", "123"]
let substringSubSets = "1234".dropLast().subSets // ["", "1", "2", "12", "3", "13", "23", "123"]


来源:https://stackoverflow.com/questions/54586161/subset-sum-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!