Permutation of String letters: How to remove repeated permutations?

前端 未结 10 2297
遇见更好的自我
遇见更好的自我 2020-12-25 08:39

Here is a standard function to print the permutations of characters of a string:

void permute(char *a, int i, int n)
{
   int j;
   if (i == n)
     printf(\         


        
10条回答
  •  长情又很酷
    2020-12-25 08:53

    Take notes which chars you swapped previously:

     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;
        }
     }
    

    This has to be the fastest one from the entries so far, some benchmark on a "AAAABBBCCD" (100 loops):

    native C             - real    0m0.547s
    STL next_permutation - real    0m2.141s
    

提交回复
热议问题