Why is the complexity of computing the Fibonacci series 2^n and not n^2?

后端 未结 9 1863
深忆病人
深忆病人 2020-11-29 05:31

I am trying to find complexity of Fibonacci series using a recursion tree and concluded height of tree = O(n) worst case, cost of each level = cn,

9条回答
  •  孤街浪徒
    2020-11-29 06:04

    The recursion tree for fib(n) would be something like :

                                  n       
                               /     \
                              n-1    n-2      --------- maximum 2^1 additions
                             /  \    /   \
                           n-2   n-3 n-3 n-4  -------- maximum 2^2 additions
                          /   \           
                         n-3 n-4              -------- maximum 2^3 additions         
                                                    ........
                                              -------- maximum 2^(n-1) additions  
    
    1. Using n-1 in 2^(n-1) since for fib(5) we will eventually go down to fib(1)
    2. Number of internal nodes = Number of leaves - 1 = 2^(n-1) - 1
    3. Number of additions = Number of internal nodes + Number of leaves = (2^1 + 2^2 + 2^3 + ...) + 2^(n-1)
    4. We can replace the number of internal nodes to 2^(n-1) - 1 because it will always be less than this value : = 2^(n-1) - 1 + 2^(n-1) ~ 2^n

提交回复
热议问题