简体   繁体   中英

What is the time complexity of this recursive algorithm?

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

My thinking is: in every recursion we have an addition operation. And we do this operation every time we divide the recursion into two. So I am not sure if I should call it O(N2^N) or O(2^N) . I think that O(N2^N) makes more sense since we are dividing the problem into 2^N pieces and adding them separately. Still though I am unsure. So can someone guide me through by showing their steps?

You can draw the calls to your functions as a binary tree:

    func3
     /\
 func3 func3
.............

You will have n levels of nodes in your binary tree, each next_level_node_count = perv_level_node_count * 2 .

That's a geometric progression.

Another approach is to form a recurrence equation for the function and solve it. The given function can be represented as

T(1) = O(1)
T(n) = 2 * T(n-1)

When you expand the recurrence as below, we get T(n) = 2^n

T(n) = 2 * { 2 * T(n-2) } = 2^2 * T(n-2)
   = 2^3 * T(n-3)
   = 2^(n-1) * T(n-(n-1))
   = 2^(n-1) * O(1)
   = 2^(n-1)
   = 2^n

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM