题意:对输入的字符串,按字典序升序输出所有种排列。
思路:这个基础就是之前将到的枚举排列问题,只不过当时是整型,这里是字符型。
注意:一个是输出的时候每组数组后都要输出一个空行(虽然你去复制sample out会发现最后一组数据没空行,但程序里的确是包括最后一组数据后都有空行)
第二是因为这里是字符型,输出的时候直接按字符串输出即可,但是需要在排列数组的最末位加‘\0‘!还有,在最开始需要对字符串排序一下。
Code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void print_permutation(int n,char *str,char *A,int cur);
int cmp_char(const void *_a, const void *_b);
char str[15];
char A[15];
int main()
{
int n;
scanf("%d",&n);
while(n-->0)
{
scanf("%s",str);
qsort(str,strlen(str),sizeof(str[0]),cmp_char);
print_permutation(strlen(str),str,A,0);
printf("\n");
}
return 0;
}
int cmp_char(const void *_a, const void *_b)
{
return *(char*)_a - *(char*)_b;
}
void print_permutation(int n,char *str,char *A,int cur)
{
if(cur==n)
{
A[cur]='\0';
printf("%s\n",A);
}
else
for(int i=0;i<n;++i)
if(!i||str[i]!=str[i-1])
{
int c1=0,c2=0;
for(int j=0;j<cur;++j) if(str[i]==A[j]) c1++;
for(int j=0;j<n;++j) if(str[i]==str[j]) c2++;
if(c1<c2)
{
A[cur]=str[i];
print_permutation(n,str,A,cur+1);
}
}
}
原文地址:http://blog.csdn.net/buxizhizhou530/article/details/43966639