Print all permutation of an array

題目:

給定一組整數array,印出所有的排列組合

EX: input: [1,2], output: [1,2], [2,1]

input: [1,2,3], output: [1,2,3],[1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]

func helper(_ arr: inout [Int], _ index: Int) {
    for i in index ..< arr.count {
        arr.swapAt(index, i)
        helper(&arr, index + 1)
        arr.swapAt(index, i)
    }
    if index == arr.count {
        print(arr)
    }
}

var arr = [1,2,3,4]
helper(&arr,0)
%d 位部落客按了讚: