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

前端 未结 4 636
慢半拍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:39

    Think of it this way:
    In each "iteration" of the recursion you do O(n) work.
    Each iteration has n-1 work to do, until n = base case. (I'm assuming base case is O(n) work)
    Therefore, assuming the base case is a constant independant of n, there are O(n) iterations of the recursion.
    If you have n iterations of O(n) work each, O(n)*O(n) = O(n^2).
    Your analysis is correct. If you'd like more info on this way of solving recursions, look into Recursion Trees. They are very intuitive compared to the other methods.

提交回复
热议问题