Time Limit: 2000 ms Case Time Limit: 2000 ms Memory Limit: 128 MB
Total Submission: 45 Submission Accepted: 7
Description
设计算法生成n个元素{r1,r2,…,rn}的全排列。n<=10
Input
包含多组输入EOF结束,每组输入包含一个只包含小写字母的字符串,长度不超过10.
Output
输出这个字符串中所有字符的全排列,按照字典序输出。
Sample Input
Original | Transformed |
abc
abc[EOL] [EOF]
Sample Output
Original | Transformed |
abc acb bac bca cab cba
#include<cstdio> #include<cmath> #include<cstring> #include<iostream> #include<string> #include<algorithm> #include<cstring> #include<set> //#define DEBUG using namespace std; const int maxn = 50050; void dfs(string list, int k, int m); void swap(char *a, char *b); set<string>s; int main() { #ifdef DEBUG freopen("Text.txt", "r", stdin); #endif // DEBUG //cin.tie(0); //cin.sync_with_stdio(false); string c; while (cin>>c) { int i; dfs(c, 0, c.size()-1); for (set<string>::iterator iter = s.begin(); iter != s.end(); iter++) cout << *iter << endl; } return 0; } void swap(char *a, char *b) { char *temp = a; a = b; b = temp; } void dfs(string list, int k, int m) { if (k == m) { s.insert(list); } else { for (int i = k; i <= m; i++) { swap(list[i], list[k]); //printf("k = %d,i = %d\n", k,i); dfs(list, k + 1, m); swap(list[i], list[k]); } } }