/*
题目描述:
有重复元素的全排列问题
输入:
有多组测试数据,每组只有一行不超过100个且不包含空格的字符组成的串
当遇到EOF标志时结束程序。
输出:
对于每组测试,输出由那组字符所能排列出来的所有组合,
按Ascii码值比较,按字典顺序输出
样例输入:
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
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
*/
这个方法不是最好的,还有耗时为0(同样的测试case)的方法。用的是stl里面的算法。
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:01
G++: Compile OK
Test 1:
Accepted Time = 0 ms
--------------------------------
Problem ID 80
Test Result
Accepted
Total Time 0 ms
Total Memory 160 Kb / 1000 Kb
Code Length 268 Bytes
*/