修改后,我们得出结论,时间复杂度实际上是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);
}
}
}
编辑:如果您希望我分解这个分析,请在下面评论。