c++ - 提高给定字符串的所有排列的时间复杂度

标签 c++ c algorithm

问题通常是给定一个字符串,打印它的所有排列。例如,字符串ABC的排列是ABC、ACB、BAC、BCA、CAB、CBA。

标准解决方案是递归解决方案,如下所示。

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

这会遇到O(n*n!)。这是我们能做的最好的事情还是有什么办法可以让它更快?

最佳答案

您可以使用std::next_permutation。请注意,它仅在排序数组上才能正常工作。
该解决方案的优点: 1)这是标准的 2)它是非递归的

这是一个示例( http://www.cplusplus.com/reference/algorithm/next_permutation/ ):

// next_permutation example
#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort

int main () {
  int myints[] = {1, 2, 3};

  std::sort (myints, myints + 3);

  std::cout << "The 3! possible permutations with 3 elements:\n";
  do {
    std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while (std::next_permutation (myints, myints + 3));

  std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}

关于c++ - 提高给定字符串的所有排列的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20991167/

相关文章:

performance - 确定由线段接触的规则二维网格中的所有单元格的最快方法是什么

c - 为什么我的归并排序程序会触发段错误?

c++ - 如何覆盖静态二进制文件的 C++ 启动函数?

c - 使用结构的邮政编码

c - 了解指针的用法

c - 如何将结构变量从客户端发送到套接字?

c++ - 没有for循环的集合中n个连续项的总和

c++ - initializeDb 中的 QPainter#drawText 段错误

c++ - 从特征匹配/单应性中过滤误报 – OpenCV

Java - 在字符串中查找第一个重复字符的最佳方法是什么