描述
You are to write a program that has to generate all possible words from a given set of letters.
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.
输入
The input consists of several words. The first line contains a number giving the number of words to follow. Each following line contains one word. A word consists of uppercase or lowercase letters from A to Z. Uppercase and lowercase letters are to be considered different. The length of each word is less than 13.
输出
For each word in the input, the output should contain all different words that can be generated with the letters of the given word. The words generated from the same input word should be output in alphabetically ascending order. An upper case letter goes before the corresponding lower case letter.
样例输入
3
aAb
abc
acba
样例输出
Aab
Aba
aAb
abA
bAa
baA
abc
acb
bac
bca
cab
cba
aabc
aacb
abac
abca
acab
acba
baac
baca
bcaa
caab
caba
cbaa
注意这道题不是按照字典序输出,而是按照题目给定的顺序输出。大写字母排在相应的小写字母前面。
这道题的思路参考: 吴永辉、王建德 算法设计编程实验 P158
这种思路让我眼前一亮的是: 它在每一层会申请一个新的数组用来标记这一层a - Z 中的字母被放置过当前位置上否。
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<vector>
#define init() ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
using namespace std;
int has[15];
char s[15],p[15];
int len;
bool cmp(char a,char b) // 根据题意写排序规则
{
char c,d;
if (a <= 'Z' && a >= 'A')
c = a - 'A' + 'a';
else c = a;
if (b <= 'Z' && b >= 'A')
d = b-'A'+'a';
else d = b;
if (c == d)
{
return a < b;
}
else return c < d;
}
void dfs(int idx){
if (idx == len){
printf("%s\n",p);
return;
}
int visit[58];
memset(visit,0,sizeof(visit));
for (int i = 0 ; i < len; ++i){
if (!visit[s[i] - 'A'] && !has[i]){
has[i] = 1;
visit[s[i] - 'A'] = 1;
p[idx] = s[i];
dfs(idx + 1);
has[i] = 0;
}
}
}
int main(){
int n;
cin>>n;
for (int i = 0 ; i < n; ++i){
memset(p,0,sizeof(p));
cin>>s;
len = strlen(s);
sort(s,s+len,cmp);
dfs(0);
}
return 0;
}