## CSDN博客

### 习题 80：全排列★★

/*

123
baca

123
132
213
231
312
321
aabc
aacb
abac
abca
acab
acba
baac
baca
bcaa
caab
caba
cbaa

*/

//给出一个字符串的所有排列,重复项过滤掉
#include "StdAfx.h"
#include <cstdlib>
#include <iostream>
using namespace std;

int len;
int flags[256];
//char max,min;

//destination, 排序后的字符串
//insrPos，字母插入位置
//len, 待排序字符串总长度
void allRank(char* destination,int insrPos,char max, char min)
{
// static int count;
int i = 0;
//recursion finished
if(insrPos == len)
{
//printf("%d:%s,len = %d, insrPos = %d/n",++count,destination, len, insrPos);
//printf("%s/n",destination);
puts(destination);
return ;
}
i = min;
while(i <= max)
{
//字母exists
if( flags[i])
{
destination[insrPos] = i;
flags[i] -= 1;
allRank(destination,insrPos+1,max,min);
flags[i] += 1;
}
i++;
}
}
void allArray(char* source)
{
int i;
char max, min;
//char *p = (char*) malloc(sizeof(char)*(len + 1));
char p[101] = {0};
len = strlen(source);
for(i = 0; i < 256; i++)
{
flags[i] = 0;
}
max = min = flags[0];
//record
for(i = 0; i < len; i++)
{

flags[source[i]] +=1;
if(max < source[i])
max = source[i];
else if(min > source[i])
min = source[i];

}

p[len] = '/0';
allRank(p,0,max,min);

//free(p);
}
int main(int argc, char *argv[])
{
char c[101];
//while(EOF!=scanf("%s",c))
while(cin >> c)
{
allArray(c);
//getchar();
}
return 0;
}
/*

79380

Name: "younthu" Problem ID "80"
Submit Time: 2008/10/02-10:55

G++: Compile Warning:
Line  In function void allArray(char*)':
Line 56: warning: array subscript has type char'

Test  1:    Accepted    Time = 20 ms
--------------------------------
Problem ID     80
Test Result    Accepted
Total Time     20 ms
Total Memory   160 Kb / 1000 Kb
Code Length    980 Bytes

*/

copy别人的源码如下：

#include <iostream>
#include <algorithm>
using namespace std;
char s[110];
int main()
{
while( scanf("%s",s)!=EOF )
{
int len = strlen(s);
sort(s,s+len);
do
{
printf("%s/n",s);
}
while(next_permutation(s,s+len));
}
return 0;
}
/*
Name: "lantionzy" Problem ID "80"Submit Time: 2008/9/21-14:01G++: Compile OKTest  1:    Accepted    Time = 0 ms--------------------------------Problem ID     80Test Result    AcceptedTotal Time     0 msTotal Memory   160 Kb / 1000 KbCode Length    268 Bytes*/

0 0