What is the space complexity of this code?

后端 未结 3 956
北海茫月
北海茫月 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:09

    Space complexity is O(n) because one side of recursion, reaches the leaves, and returns up, until the root, similar happens for the other side of recursion and in every middle step, the space used in the recursion cannot be bigger than O of depth of recursion tree.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-12 01:23

    Because the second f(n-1) can't run until the first one completes (or vice versa -- it's the same either way). The first call will recurse n times, then all those will return, so that will push a total of n stack frames. Then the second call will do the same thing.

    So it never gets more than n levels deep in the recursion, and that's the only contributor to space complexity.

    0 讨论(0)
提交回复
热议问题