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

时间:2015-04-13 11:48:32

标签: 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;
}

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

谢谢..: - )

2 个答案:

答案 0 :(得分:6)

标准中有

#include<algorithm>
std::vector<int> vec;
std::next_permutation(std::begin(vec), std::end(vec));

如果是字符串

# include<string>
#include<algorithm>

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

} while(std::next_permutation(std::begin(str), std::end(str)));

答案 1 :(得分:1)

没有比O(n * n!)更快的算法,因为你必须枚举所有的n!可能性,每次都要处理n个字符。

你的algoirthm也以O(n * n!)复杂度运行,因为它可以在http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/

中看到
相关问题