分析
给一串,要求输出其字典序全排列。
相对需要注意的是,该串可能有重复数字,并且不应输出重复的排列。
这里可以在填充每一格的时候,检查一下当前已经填充的格子里和这格相同的有几个,判断有没有超过给定串里头的限定个数,如果没有可以填充。
另外不能重复,可以考虑使用这一格前,检查上一次使用的格是不是和这格内容一致,如果一致那么因为只考虑内容重复,会导致再输出一组重复排列。
当然,使用next_permutation()
也是好方法。
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
using std::next_permutation;
using std::sort;
char s[50];
int main()
{
int t;
scanf("%d", &t);
while (t--) {
scanf("%s", s);
sort(s, s+strlen(s));
do {
printf("%s\n", s);
} while (next_permutation(s, s+strlen(s)));
printf("\n");
}
return 0;
}
#include <cstdio>
#include <cstring>
#include <algorithm>
using std::sort;
char s[50], a[50];
int l;
void print_permutation(int cur)
{
if (cur == l) {
a[cur] = '\0';
printf("%s\n", a);
return;
}
else {
for (int i = 0; i < l; i++)
if (!i || s[i] != s[i-1]) {
int c1 = 0, c2 = 0;
for (int j = 0; j < cur; j++) if (s[i] == a[j]) c1++;
for (int j = 0; j < l; j++) if (s[i] == s[j]) c2++;
if (c1 < c2) {
a[cur] = s[i];
print_permutation(cur+1);
}
}
}
}
int main()
{
int t;
scanf("%d", &t);
while (t--) {
scanf("%s", s);
l = strlen(s);
sort(s, s+l);
print_permutation(0);
printf("\n");
}
return 0;
}
题目
Description
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