查找字符串的所有可能排列

Gok*_*l M 4 c c++ arrays string algorithm

我有以下程序来查找字符串的所有可能的排列.

#include <stdio.h>

 /* Function to swap values at two pointers */
 void swap (char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

/* Function to print permutations of string
   This function takes three parameters:
   1. String
   2. Starting index of the string
   3. Ending index of the string. */
void permute(char *a, int i, int n)
{
   int j;
   if (i == n)
       printf("%s\n", a);
   else
   {
       for (j = i; j <= n; j++)
       {
          swap((a+i), (a+j));
          permute(a, i+1, n);
          swap((a+i), (a+j)); //backtrack
       }
   }
}

/* Driver program to test above functions */
int main()
{
   char a[] = "abcd";
   permute(a, 0, 3);
   getchar();
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

我需要知道有没有更好的方法(有效)找到所有排列,因为这个算法具有O(n ^ n)效率.

谢谢.. :-)

Ste*_*hen 6

它是标准的

#include<algorithm>
std::vector<int> vec;
std::next_permutation(std::begin(vec), std::end(vec));
Run Code Online (Sandbox Code Playgroud)

如果是字符串

# include<string>
#include<algorithm>

std::string str ="abcd"
do{
     std::cout<<str<<"\n";

} while(std::next_permutation(std::begin(str), std::end(str)));
Run Code Online (Sandbox Code Playgroud)