提高给定字符串所有排列的时间复杂度
Improving the time complexity of all permutations of a given string
这个问题通常被提出为给定一个字符串,打印它的所有排列。例如,字符串ABC的排列是ABC,ACB,BAC,BCA,CAB,CBA。
标准解决方案是递归解决方案,如下所示。
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%sn", 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;
}
您正在寻找的结果包含 n*n 个元素,所以这是你能得到的最好的!
假设您有n
元素,并且正在寻找k
个排列0 <= k <= n-1
。
- 创建一个包含所有元素和空列表
result
的列表elements
-
while elements not empty
:- 设置
p = k % elements.size
和k = k / elements.size
- 删除
elements[p]
并将其附加到result
- 设置
我们只访问elements
的每个元素一次,所以它是 O(n)。
std::next_permutation
可以完成这项工作:
#include <algorithm>
#include <iostream>
int main () {
char s[] = "BAC";
// let's begin with the lowest lexicographically string.
std::sort(std::begin(s), std::end(s) - 1); // '- 1' : ignore ' '
do {
std::cout << s << std::endl;
} while (std::next_permutation(std::begin(s), std::end(s) - 1));
return 0;
}
相关文章:
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 我可以创建一个包含两个变量的 for 循环,但时间复杂度仍然为 O(n) 吗?
- 函数的时间复杂度是多少?
- 如何检查两个 std::向量在小于 O(n) 的时间复杂度内是否相等
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 如何计算此排序函数的时间复杂度?
- 计算两个代码块的时间复杂度
- C++ 中具有 O(1) 搜索时间复杂度的数据结构
- 具有嵌套 if-else 的循环的时间复杂度
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- 如何计算函数的时间复杂度?
- 求解包含"variables"的 T(n) 时间复杂度
- 查找数字是否为 2 的幂的时间复杂度
- C++ - 最坏情况和平均情况插入时间复杂度在 std::unordered_map <int,int>?
- 为什么一种算法在相同的时间复杂度下比另一种算法更快?
- 关于记忆后这种递归关系的时间复杂度
- 2 个嵌套循环的时间复杂度
- 给定C++代码的时间复杂度是多少?
- 提高给定字符串所有排列的时间复杂度