How to solve: T(n) = T(n - 1) + n

前端 未结 4 629
慢半拍i
慢半拍i 2020-12-03 22:00

I have the following worked out:

T(n) = T(n - 1) + n = O(n^2)

Now when I work this out I find that the bound is very loose. Have I done so

4条回答
  •  伪装坚强ぢ
    2020-12-03 22:38

    The solution is pretty easy for this one. You have to unroll the recursion:

    T(n) = T(n-1) + n = T(n-2) + (n - 1) + n = 
    = T(n-3) + (n-2) + (n-1) + n = ... =
    = T(0) + 1 + 2 + ... + (n-1) + n 
    

    You have arithmetic progression here and the sum is 1/2*n*(n-1). Technically you are missing the boundary condition here, but with any constant boundary condition you see that the recursion is O(n^2).

提交回复
热议问题