import Foundation
func stringPermutations(_ str: String) -> [String] {
var result = [String]()
var chars = Array(str)
stringPermutationsCreate(&chars, 0, &result)
return result
}
private func stringPermutationsCreate(_ chars: inout [Character], _ index: Int, _ result: inout [String]) {
if index == chars.count {
result.append(String(chars))
return
}
for i in index..<chars.count {
chars.swapAt(index, i)
stringPermutationsCreate(&chars, index + 1, &result)
chars.swapAt(index, i) // backtrack
}
}
let s = "abc"
let permutations = stringPermutations(s)
print(permutations)
/*
run:
["abc", "acb", "bac", "bca", "cba", "cab"]
*/