【问题标题】:Finding all possible permutation of a string查找字符串的所有可能排列
【发布时间】:2015-06-18 17:14:54
【问题描述】:

我有以下程序用于查找字符串的所有可能排列。

#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)。

谢谢你.. :-)

【问题讨论】:

  • 你为什么不用std::next_permutation
  • 我假设您使用的是 C,而不是 C++(尽管有额外的标记),否则您可以使用来自 &lt;algorithm&gt;std::next_permutation
  • 如果您实际使用的是 C 而不是 C++,您可以将代码 here 改编为 C 代码。这篇文章是你将如何实现 next_permutation 函数。

标签: c++ c arrays string algorithm


【解决方案1】:

在标准中是有的

#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)));

【讨论】:

  • 我愿意在早上喝咖啡打赌 OP 正在使用 C,并且无缘无故地标记了 C++
【解决方案2】:

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

您的算法也以 O(n* n!) 复杂度运行,如 http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/ 中所示

【讨论】:

  • 如果你想真正输出每个排列,你无法击败 O(n * n!),但实际上你可以更快地生成它们,只使用一次交换从当前排列生成下一个排列:en.wikipedia.org/wiki/…。有了 Even 的加速,这总共只需要 O(n!)。
猜你喜欢
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多