0%

字符串的排列

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串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
class Solution {
public:
string text;
vector<string> result;
void swap(const int a, const int b)
{
if (a != b)
{
const char char_a = text[a];
text[a] = text[b];
text[b] = char_a;
}
}
void DoPermutation(const int start)
{
if (start == text.length() - 1)
{
result.push_back(text);
}
else
{
for (int i = start; i < text.length(); i++)
{
if (i == start || text[i] != text[start])
{
swap(start, i);
DoPermutation(start + 1);
swap(start, i);
}
}
}
}
vector<string> Permutation(string str) {
text = str;
DoPermutation(0);
sort(result.begin(), result.end());
return result;
}
};