What is the space complexity of this code?

后端 未结 3 983
北海茫月
北海茫月 2021-01-12 00:46
int f(int n)
{ 
    if (n <= 1)
    { 
         return 1;
    } 
    return f(n - 1) + f(n - 1);
} 

I know that the time complexity is O(2

3条回答
  •  情书的邮戳
    2021-01-12 01:14

    Draw the exponential time complexity tree and the length of path of any leaf from the root of the tree will be linear. This linear path is the space complexity of the algorithm. The algorithm will traverse each of those paths to solve the problem but at any point the maximum number of recursive calls stored in the stack will be linear. Ex: for f(3)

             3 
           /   \ 
         2      2 
        / \    / \ 
       1   1  1   1
    

    The maximum length from root to leaf is O(n). Thus, the space complexity is also O(n).

提交回复
热议问题