How to find subset sum

[Question] : Find subset sum in given Array
Example: Input: N = 6 arr[] = {3, 34, 4, 12, 5, 2} sum = 9 Output: 1 Explanation: Here there exists a subset with sum = 9, 4+3+2 = 9.

func sumSubSet(ind: Int, sum: Int, op: inout [Int], inArray: [Int],n: Int) {
    if ind == n {
        op.append(sum)
        return
    }
    // Pick An Element
    sumSubSet(ind: ind+1, sum: sum+inArray[ind], op: &op, inArray: inArray, n: n)
    // Not Pick An Element
    sumSubSet(ind: ind+1, sum: sum, op: &op, inArray: inArray, n: n)
}


//Input: candidates = , target = 8
let inArray = [2,3]
var op: [Int] = []
let n = 2
sumSubSet(ind: 0, sum: 0, op: &op, inArray: inArray, n: n)
print(op.sorted())

Leave a Comment

Your email address will not be published. Required fields are marked *