Swift 全排列經典算法

func permutations3(_ arr: inout [Int], start: Int, end: Int) {
    if start == end - 1 { // if start equal to last element, meaning nothing need to be swap anymore
        print(arr) // output the array
    } else {
        for current in start..<end {
            (arr[start], arr[current]) = (arr[current], arr[start]) // swap each element to the start
            permutations3(&arr, start: start + 1, end: end) // recurse exept the start
            (arr[start], arr[current]) = (arr[current], arr[start]) // back track
        }
    }
}

print("--------------------")
var data3 = [1, 2, 3]
permutations3(&data3, start: 0, end: data3.count)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章