原题:
Generating permutation has always been an important problem in computer science. In this problem
you will have to generate the permutation of a given string in ascending order. Remember that your
algorithm must be efficient.
Input
The first line of the input contains an integer n, which indicates how many strings to follow. The next
n lines contain n strings. Strings will only contain alpha numerals and never contain any space. The
maximum length of the string is 10.
Output
For each input string print all the permutations possible in ascending order. Not that the strings should
be treated, as case sensitive strings and no permutation should be repeated. A blank line should follow
each output set.
Sample Input
3
ab
abc
bca
Sample Output
ab
ba
abc
acb
bac
bca
cab
cba
abc
acb
bac
bca
cab
cba
中文:
给你一个字符串,让你输出这个字符串按字典序的所有排列。
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=11;
char s[maxn],ans[maxn];
void permutation(int n,int cur,char *p,char *a)
{
if(cur==n)
{
for(int i=0;i<n;i++)
cout<<a[i];
cout<<endl;
}
else
{
for(int i=0;i<n;i++)
{
if(!i||p[i]!=p[i-1])
{
int c1=0,c2=0;
for(int j=0;j<cur;j++)
if(a[j]==p[i])
c1++;
for(int j=0;j<n;j++)
if(p[j]==p[i])
c2++;
if(c1<c2)
{
a[cur]=p[i];
permutation(n,cur+1,p,a);
}
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--)
{
cin>>s;
int len=strlen(s);
sort(s,s+len);
permutation(len,0,s,ans);
//if(t)
cout<<endl;
}
return 0;
}
解答:
裸题,套小白书里的模板即可