简体   繁体   English

具有嵌套迭代函数的递归算法的时间复杂度?

[英]Time complexity of a recursive algorithm with nested iterative function?

a) 一个)

void f(n){
  if(n<=1) return;
    else{
      g(n); //g(n) is O(N^2).
      f(n/2);
      f(n/2);
    } 
}

b) b)

void f(n){
  if(n<=1) return;
    else{
      g(n); //g(n) is O(N).
      f(n-1);
      f(n-1);
    } 
}

c) C)

void f(n){
  if(n<=1) return;
    else{
      g(n); //g(n) is O(N^2).
      f(n-1);
      f(n-1);
    } 
}

How do I count the O(n) complexity of the above two code snippet? 如何计算上述两个代码段的O(n)复杂度?

a) I got the answer O(n^2), because each f(n) calls itself twice recursively. a)我得到了答案O(n ^ 2),因为每个f(n)递归地调用自己两次。 And since the depth of the tree is LogN (n/2), the overall complexity is O(n^2), do i disregard the g(n) method since it is N^2 as well? 并且由于树的深度是LogN(n / 2),总体复杂度是O(n ^ 2),我是否忽略g(n)方法,因为它也是N ^ 2?

b) Since the depth of the tree is N, and each f(n) calls itself twice recursively. b)由于树的深度是N,并且每个f(n)递归地称自己两次。 And since each level needs to perform g(n) operation N times, I got the answer O(N.2^(N)). 并且由于每个级别需要执行N次操作g(n),我得到了答案O(N.2 ^(N))。

c) Same as b) but g(n) is performed N^2 time - hence O(N^2.2^(N)). c)与b)相同但是g(n)在N ^ 2时间内进行 - 因此O(N ^ 2.2 ^(N))。

Is this correct? 它是否正确?

a) The recursive equation is as bellow. a)递归方程如下所示。

If you expand the recursion we have: 如果你展开递归,我们有:

So we want to calculate last equation which is equal to: 所以我们想要计算最后的等式,它等于:

Since the last part of above equation is a geometric serie we have: 由于上面等式的最后一部分是几何系列,我们有:

So the recursion is 所以递归是 .

b) The approach is same as before. b)方法与以前相同。

which is equal to: 等于:

So the answer is 所以答案是

c) Third part can solve with the same technique. c)第三部分可以用相同的技术解决。

PS: Thanks to Alexandre Dupriez for his comment. PS:感谢Alexandre Dupriez的评论。

PS: For an elegant simplification of the summation read Alexandre 's comments bellow. PS:对于总结的优雅简化,阅读亚历山大的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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