How to Generate subarrays using recursion

[Question]: We haveGiven an array, generate all the possible subarrays of the given array using recursion for example :

  n = 3   Array =  [1,2,3]  Output = [1, 2, 3] [1, 2] [1, 3] [1] [2, 3] [2] [3] []
func printAllSequence(currentIndex: Int, op: inout [Int], inArray: [Int],length: Int) {
    if currentIndex == length {
        print(op)
        return
    }
    op.append(inArray[currentIndex])
    printAllSequence(currentIndex: currentIndex+1, op: &op, inArray: inArray, length: length)
    op.removeLast()
    printAllSequence(currentIndex: currentIndex+1, op: &op, inArray: inArray, length: length)
}


var inArray = [4,2,9]
var length = inArray.count
var op: [Int] = []
var currentIndex = 0
printAllSequence(currentIndex: currentIndex, op: &op, inArray: inArray, length: length)
It prints --> [4, 2, 9] [4, 2] [4, 9] [4] [2, 9] [2] [9] []

Leave a Comment

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