Recursion 使用递归反转堆栈的时间复杂性

Recursion 使用递归反转堆栈的时间复杂性,recursion,time-complexity,Recursion,Time Complexity,我试图找出以下代码的时间复杂性 int insert_at_bottom(int x, stack st) { if(st is empty) { st.push(x) } else { int a = st.top() st.pop() insert_at_bottom(x) st.push(a) } } void reverse(stack st) { if(st is not empty) { int st = st.top(

我试图找出以下代码的时间复杂性

int insert_at_bottom(int x, stack st) {
if(st is empty) {
    st.push(x)
}
else {
    int a = st.top()
    st.pop()
    insert_at_bottom(x)
    st.push(a)
}
}
void reverse(stack st) {
    if(st is not empty) {
        int st = st.top()
        st.pop()
        reverse(st)
        insert_at_bottom(x, st)
    }
}
// driver function
int[] reverseStack(int[] st) {
    reverse(st)
    return st
}
对于堆栈顶部的每个元素,我们将弹出整个堆栈,将顶部的元素放置在底部,这需要进行O(n)操作。这些O(n)操作是对堆栈中的每个元素执行的,所以时间复杂度应该是O(n^2)


然而,我想从数学上找到时间复杂性。我试图找到递归关系,得到了T(n)=2T(n-1)+1。这可能是错误的,因为第二个函数调用的时间复杂度不应被视为T(n-1)。

您的论证大体上是正确的。如果在底部插入需要O(n)时间,那么反向函数需要O(n2)时间,因为它对每个元素的堆栈执行线性时间操作

但是
reverse()
的重复关系看起来有点不同。在每个步骤中,您要做三件事:

  • 称自己为n-1
  • O(n)时间操作(
    在底部插入()
  • 一些固定时间的东西
  • 因此,你可以把这些加起来。所以我认为它可以写成:

    T(n)=T(n-1)+n+c,其中c是一个常数

    你会发现,由于递归,T(n-1)=T(n-2)+n-1+c。因此,如果在n>0的情况下继续以这种方式扩展整个系列,则可以获得:

    T(n)=1+…+n-1+n+nc

    自1+2+…+n) =n(n+1)/2(见),我们得到

    T(n)=n(n+1)/2+nc=n2/2+n/2+nc=O(n2)。□


    在底部插入的O(n)时间()
    ,您可以用类似的方式显示。

    谢谢,我明白了!我们不认为插入式AT~(?)底()函数是t(n-1)时间复杂度,而只是n。我对for循环使用相同的逻辑。不客气!您会发现,即使对于
    insert\u-at\u-bottom
    ,您的循环逻辑也可以通过递归函数得到验证。它是T(n)=T(n-1)+c,其中c是一个常数。您将获得c+c+c..=nc=O(n)