給定字符串,輸出其所有不重複的全排列,按字典序排列。字符串可能包含重複字符。
next_permutation 會自動處理重複元素,生成嚴格遞增的字典序排列。只需先 sort,然後 do { ... } while (next_permutation(...))。
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
char str[205];
int main() {
while (cin >> str) {
int len = strlen(str);
sort(str, str + len);
do {
cout << str << endl;
} while (next_permutation(str, str + len));
}
return 0;
}
若不使用 STL,需在 DFS 中跳過同層重複字符:
i > 0 && a[i] == a[i-1] && !used[i-1] 則 continue(關鍵剪枝)O(k * n),k 為不重複排列數