| 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;
}
字母重组算法

本文介绍了一种使用回溯法实现字母重组的算法,该算法能够从给定的一组字母中生成所有可能的不同排列,并确保输出结果的字典序。文中提供了详细的代码实现,包括通过比较函数处理大小写字母的方法。
251

被折叠的 条评论
为什么被折叠?



