Print one sequence whose sum is K

[Question] : Print any one sequence whose some is equal to K
For example:- [4,8,4] Target Sum = 8 So Output will be [4,4]

func printOneSeqSumK(ind: Int,
                     op: inout [Int],
                     targetSum: Int,
                     currSum: inout Int,
                     inArray: [Int],
                     length: Int) -> Bool {
    if ind == length {
        if  targetSum == currSum {
            print("foundTheSum-->", op)
            return true
        }
        return false
    }

    op.append(inArray[ind])
    currSum += inArray[ind]

    if printOneSeqSumK(ind: ind+1,
                    op: &op,
                    targetSum: targetSum,
                    currSum: &currSum,
                    inArray: inArray,
                       length: length) { return true}
    op.removeLast()
    currSum -= inArray[ind]
    if printOneSeqSumK(ind: ind+1,
                    op: &op,
                    targetSum: targetSum,
                    currSum: &currSum,
                    inArray: inArray,
                       length: length) { return true }
    return false
}


let arrayInput = [4,8,4]
let length = arrayInput.count
var op: [Int] = []
let ind = 0
let targetSum = 8
var currSum = 0
printOneSeqSumK(ind: ind,
                op: &op,
                targetSum: targetSum,
                currSum: &currSum,
                inArray: arrayInput,
                length: length)

Leave a Comment

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