The complexity of the recursive function space

Given the following function:

int f(int n) {
  if (n <= 1) {
    return 1;
  }
  return f(n - 1) + f(n - 1);
} 

I know the complexity of time is Big O O(2^N), because every call invokes a function twice.

I do not understand why the complexity of space / memory O(N)?

+21
source share
1 answer

A useful way to solve this type of problem is to think of a recursion tree . Two functions of a recursive function for identification:

  1. Tree depth (how many total return statements will be executed before the base case)
  2. Tree width (how many total recursive function calls will be made )

T(n) = 2T(n-1). , O(2^n), .

      C
     / \         
    /   \      
T(n-1)  T(n-1)

            C
       ____/ \____
      /           \
    C              C   
   /  \           /  \
  /    \         /    \
T(n-2) T(n-2) T(n-2)  T(n-2)

, .

n 1. , n, . 2 n , 2^n, O(2^n).

, . , O(recursion depth). , n , , , O(n).

+32

Source: https://habr.com/ru/post/1674383/


All Articles