Find combination of sum possibilities

[Question]: In a distinct array a target integer target, return a list of all unique combinations of  candidate
Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]]

func seqCombinationWithSumK(ind: Int,
                            target: Int,
                            op: inout [Int],
                            inArray: [Int],
                            length: Int,
                            ans: inout [[Int]]) {
    if ind == length {
        if target == 0 {
            ans.append(op)
        }
        return
    }
    // Pick An Element
    if (inArray[ind] <= target) {
        op.append(inArray[ind])
        seqCombinationWithSumK(ind: ind,
                               target:target - inArray[ind],
                               op: &op,
                               inArray: inArray,
                               length: length,
                               ans: &ans)
        op.removeLast()
    }
    // Not Pick condition.
    seqCombinationWithSumK(ind: ind+1,
                           target:target,
                           op: &op,
                           inArray: inArray,
                           length: length,
                           ans: &ans)
}


let inArray = [2,3,6,7]
let length = inArray.count
var op: [Int] = []
var ans: [[Int]] = []
let currentIndex = 0
let target = 7
seqCombinationWithSumK(ind: currentIndex,
                       target: target,
                       op: &op,
                       inArray: inArray,
                       length: length,
                       ans: &ans)

print("answer,", ans)

Leave a Comment

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