题目描述:
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
题意:
求全排列
题解:
注意一下优先级:‘A’<‘a’<‘B’<‘b’<…<‘Z’<‘z’.
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s[1000];
int cmp(const char& a, const char& b){
int x1 = a;
int x2 = b;
if (x1 >= 'A' && x1 <= 'Z')
x1 = (x1-'A')*2;
else
x1 = (x1-'a')*2+1;
if (x2 >= 'A' && x2 <='Z')
x2 = (x2-'A')*2;
else
x2 = (x2-'a')*2+1;
return x1 < x2;
}
int main(){
int t;
scanf("%d",&t);
while (t--){
scanf("%s",s);
sort(s,s+strlen(s),cmp);
printf("%s\n",s);
while (next_permutation(s,s+strlen(s),cmp)){
printf("%s\n",s);
}
}
return 0;
}

本文深入解析了一种全排列算法,通过实例演示了如何从给定的一组字母中生成所有可能的单词组合。代码示例使用C++实现,展示了如何通过sort和next_permutation函数生成并按字母顺序输出所有唯一单词。

445

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



