Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 12070 | Accepted: 4933 |
Description
Example: Given the word "abc", your program should - by exploring all different combination of the three letters - output the words "abc", "acb", "bac", "bca", "cab" and "cba".
In the word taken from the input file, some letters may appear more than once. For a given word, your program should not produce the same word more than once, and the words should be output in alphabetically ascending order.
Input
Output
Sample Input
3 aAb abc acba
Sample Output
Aab Aba aAb abA bAa baA abc acb bac bca cab cba aabc aacb abac abca acab acba baac baca bcaa caab caba cbaa
Hint
So the right order of letters is 'A'<'a'<'B'<'b'<...<'Z'<'z'.
Source
回溯法
#include<stdio.h>
#include<algorithm>
#include<cctype>
using namespace std;
char s[20];
char res[20];
bool b[20];
int N;
int cmp(char a,char b)
{
if(islower(a)&&islower(b)) return a<b;
if(isupper(a)&&isupper(b)) return a<b;
if(islower(a)&&isupper(b)) return a<(b-'A'+'a');
if(isupper(a)&&islower(b)) return a<=(b-'a'+'A');
}
void backtrace(int n)
{
if(n==N)
{
printf("%s/n",res);
return ;
}
int i;
for(i=0; i<N; ++i)
{
if(b[i]==false)
{
res[n]=s[i];
b[i]=true;
backtrace(n+1);
b[i]=false;
while(i<(N-1) && s[i]==s[i+1])//跳过相同的字符
i++;
}
}
}
int main()
{
int T;
while(scanf("%d",&T)!=EOF)
{
while(T--)
{
scanf("%s",&s);
N=strlen(s);
res[N]='/0';
sort(s,s+N,cmp);
memset(b,0,sizeof(b));
backtrace(0);
}
}
return 0;
}