题目:确定某字符串的全部排列组合.
核心代码:
func getPerms(str:String) -> [String] {
var permutations:[String] = []
if str.characters.count == 0 {
permutations.append("")
return permutations
}
let first:String = str[0]
let index = str.index(str.startIndex, offsetBy: 1)
let remainder:String = str.substring(from: index)
let words:[String] = getPerms(str: remainder)
for word in words {
for i in 0...word.characters.count {
let str:String = insertCharAt(word: word, mid: first, i: i)
permutations.append(str)
}
}
return permutations
}
func insertCharAt(word:String,mid:String,i:Int) -> String {
let index = word.index(word.startIndex, offsetBy: i)
let start:String = word.substring(to: index)
let end:String = word.substring(from: index)
let result = start + mid + end
return result
}
测试代码:
var permutations:[String] = recursion.getPerms(str: "abc")
print("FlyElephant---字符串排列:\(permutations)")
FlyElephant.png
网友评论