Computational complexity of Fibonacci Sequence

后端 未结 11 1472
慢半拍i
慢半拍i 2020-11-21 10:27

I understand Big-O notation, but I don\'t know how to calculate it for many functions. In particular, I\'ve been trying to figure out the computational complexity of the nai

11条回答
  •  一个人的身影
    2020-11-21 10:32

    Recursive algorithm's time complexity can be better estimated by drawing recursion tree, In this case the recurrence relation for drawing recursion tree would be T(n)=T(n-1)+T(n-2)+O(1) note that each step takes O(1) meaning constant time,since it does only one comparison to check value of n in if block.Recursion tree would look like

              n
       (n-1)      (n-2)
    (n-2)(n-3) (n-3)(n-4) ...so on
    

    Here lets say each level of above tree is denoted by i hence,

    i
    0                        n
    1            (n-1)                 (n-2)
    2        (n-2)    (n-3)      (n-3)     (n-4)
    3   (n-3)(n-4) (n-4)(n-5) (n-4)(n-5) (n-5)(n-6)
    

    lets say at particular value of i, the tree ends, that case would be when n-i=1, hence i=n-1, meaning that the height of the tree is n-1. Now lets see how much work is done for each of n layers in tree.Note that each step takes O(1) time as stated in recurrence relation.

    2^0=1                        n
    2^1=2            (n-1)                 (n-2)
    2^2=4        (n-2)    (n-3)      (n-3)     (n-4)
    2^3=8   (n-3)(n-4) (n-4)(n-5) (n-4)(n-5) (n-5)(n-6)    ..so on
    2^i for ith level
    

    since i=n-1 is height of the tree work done at each level will be

    i work
    1 2^1
    2 2^2
    3 2^3..so on
    

    Hence total work done will sum of work done at each level, hence it will be 2^0+2^1+2^2+2^3...+2^(n-1) since i=n-1. By geometric series this sum is 2^n, Hence total time complexity here is O(2^n)

提交回复
热议问题