Kum*_*lok 11 c c++ algorithm permutation
这是打印字符串字符排列的标准函数:
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j < n; j++) //check till end of string
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
}
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
Run Code Online (Sandbox Code Playgroud)
它工作正常,但有一个问题,它还打印一些重复的排列,exapmle:
如果字符串是"AAB"
输出是:
AAB
ABA
AAB
ABA
BAA
BAA
Run Code Online (Sandbox Code Playgroud)
这也有3个重复的条目.
有没有办法防止这种情况发生?
-
谢谢
Alok Kr.
Kar*_*ath 13
记下您之前交换过的字符:
char was[256];
/*
for(j = 0; j <= 255; j++)
was[j] = 0;
*/
bzero(was, 256);
for (j = i; j <= n; j++)
{
if (!was[*(a+j)]) {
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack
was[*(a+j)] = 1;
}
}
Run Code Online (Sandbox Code Playgroud)
这是迄今为止参赛作品中速度最快的一个,"AAAABBBCCD"(100个循环)的一些基准:
native C - real 0m0.547s
STL next_permutation - real 0m2.141s
Run Code Online (Sandbox Code Playgroud)