题目描述:输入一个字符串,按字典序打印出该字符串中字符的所有排列
例如输入字符串abc,
则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
结果请按字母顺序输出。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| import Foundation
class For28Solution { func permutation(_ s: String) { let temp:[Character] = Array(s) full_permutation(arr: temp, begin: 0, end: temp.count) } // 去重 func isSwap(arr: [Character], begin: Int, end: Int) -> Bool { var result:Bool = true for i in begin..<end { if arr[i] == arr[end] { result = false break } } return result } // 字符串特定区间的字符串排列 func full_permutation(arr: [Character], begin: Int, end: Int) { var temp:[Character] = arr if begin == end - 1 { // 递归之后输出 let data:[Character] = Array(arr[0..<end]) print("排列---\(data)") } else { for i in begin..<end { if isSwap(arr: temp, begin: begin, end: i) { temp.swapAt(i, begin) // 字符串交换 full_permutation(arr: temp, begin: begin+1, end: end) temp.swapAt(i, begin) // 字符串恢复
}
} } } }
|
算法思想:首先,求所有可能出现在第一个位置的字符,
其次,把第一个字符和其后面的字符一一交换。如下图所示,分别把第一个字符a和后面的b、c等字符交换的情形。
接着,固定第一个字符,求后面所有字符的排列。这个时候我们仍把后面的所有字符分成两部分:后面字符的第一个字符,以及这个字符之后的所有字符。然后把第一个字符逐一和它后面的字符交换
github地址:https://github.com/cubegao/LeetCode