递归字符串排列函数的复杂度
这个函数的复杂度是多少???
void permute(string elems, int mid, int end)
{
static int count;
if (mid == end) {
cout << ++count << " : " << elems << endl;
return ;
}
else {
for (int i = mid; i <= end; i++) {
swap(elems, mid, i);
permute(elems, mid + 1, end);
swap(elems, mid, i);
}
}
}
From: Are there any better methods to do permutation of string?
what is the complexity of this function???
void permute(string elems, int mid, int end)
{
static int count;
if (mid == end) {
cout << ++count << " : " << elems << endl;
return ;
}
else {
for (int i = mid; i <= end; i++) {
swap(elems, mid, i);
permute(elems, mid + 1, end);
swap(elems, mid, i);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
忽略打印,满足的递推关系是
T(n) = n*T(n-1) + O(n)
If
G(n) = T(n)/n!
我们得到G(n) = G(n-1) + O(1/(n-1)!)
给出
G(n) = Theta(1)
。因此
T(n) = Theta(n!)
。假设打印恰好发生
n!
次,我们得到的时间复杂度为Theta(n * n!)
Ignoring the print, the recurrence relation satisfied is
T(n) = n*T(n-1) + O(n)
If
G(n) = T(n)/n!
we getG(n) = G(n-1) + O(1/(n-1)!)
which gives
G(n) = Theta(1)
.Thus
T(n) = Theta(n!)
.Assuming that the print happens exactly
n!
times, we get the time complexity asTheta(n * n!)
在不深入研究您的代码的情况下,我想我可以有合理的信心地说它的复杂性是 O(n!)。这是因为任何枚举 n 个不同元素的所有排列的有效过程都必须迭代每个排列。有n个!排列,因此算法必须至少为 O(n!)。
编辑:
这实际上是 O(n*n!)。感谢@templatetypedef 指出了这一点。
Without looking too deeply at your code, I think I can say with reasonable confidence that its complexity is O(n!). This is because any efficient procedure to enumerate all permutations of n distinct elements will have to iterate over each permutation. There are n! permutations, so the algorithm has to be at least O(n!).
Edit:
This is actually O(n*n!). Thanks to @templatetypedef for pointing this out.
这将计算算法的复杂度。
实际上 O(N) 是
N!!! = 1 * 3 * 6 * ... * 3N
This will calculate complexity of the algorithm.
Actualy O(N) is
N!!! = 1 * 3 * 6 * ... * 3N