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)
Swift 全排列经典算法
最新推荐文章于 2020-08-08 14:05:53 发布