题意:给定几个小写字母(含重复),按照字典序输出其全排列
思路:深搜。用C++库函数更简洁。
输入:
bbjd
输出:
bbdj
bbjd
bdbj
bdjb
bjbd
bjdb
dbbj
dbjb
djbb
jbbd
jbdb
jdbb
#include <stdio.h>
#include <string.h>
#define N 202
#define M 26
char t[N];
int used[M],len;
void dfs(int lev){
int i;
if(lev == len){
puts(t);
return ;
}
for(i = 0;i<M;i++)
if(used[i]){
t[lev] = 'a'+i;
used[i]--;
dfs(lev+1);
used[i]++;
}
}
int main(){
freopen("a.txt","r",stdin);
while(scanf("%s",t)!=EOF){
int i;
memset(used,0,sizeof(used));
len = strlen(t);
for(i = 0;i<len;i++)
used[t[i]-'a']++;
dfs(0);
}
return 0;
}
C++库函数:
#include<iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
int main(){
char str[205];
freopen("a.txt","r",stdin);
freopen("b.txt","w",stdout);
while(scanf("%s",str)!=EOF){
sort(str,str+strlen(str));
printf("%s\n",str);
while(next_permutation(str,str+strlen(str)))
printf("%s\n",str);
}
system("pause");
}