【发布时间】:2016-02-23 09:12:52
【问题描述】:
修改后得出结论,时间复杂度其实是O(2^n)
问题是时间复杂度是多少?是 O(2^n) 还是?
我相信这是因为 for 循环被认为运行了 n 次。然后嵌套的 while 循环运行 2^n 次。第二个 while 循环运行 2^n 次。
Algorithm subsetsGenerator(T)
Input: A set T of n elements
Output: All the subsets of T stored in a queue Q {
create an empty queue Q;
create an empty stack S;
let a1, a2, …, an be all the elements in T;
S.push({}); // Push the empty subset into the stack
S.push({a1})
for ( each element ai in T-{a1} )
{
while (S is not empty )
{
x=S.pop;
Q.enqueue(x);
x=x ∪ { ai };
Q.enqueue(x);
}
if ( ai is not the last element )
while (Q is not empty )
{
x=Q.dequeue();
S.push(x);
}
}
}
编辑:如果你想让我分解分析,请在下面评论。
【问题讨论】:
-
你知道输出有多大吗?产生这么大的输出需要多长时间,一次将元素添加到输出中?你和你的朋友都分析错了。
-
是的,我们仍在考虑它,但是我们正在使用一组 4 个元素对其进行分析。如果我们再看一遍,每个 while 循环给出 2^n,而 for 循环只给出一个 n。
-
这里有问题吗?
标签: big-o