另一个递归函数内的递归函数的复杂性

时间:2017-11-06 15:43:17

标签: algorithm big-o

我无法弄清楚这个练习的解决方案:

计算f(g(n))+ g(f(n))的复杂度,g和f定义如下:

int f(int x) {
 if (x<=1) return 2;
 int a = g(x) + 2*f(x/2);
 return 1+ x + 2*a;
}

int g(int x) {
int b=0;
 if (x<=1) return 5;
     for (int i=1, i<=x*x;i++)
         b+=i;
 return b + g(x-1);
}

任何人都可以解释我如何找到解决方案吗?

1 个答案:

答案 0 :(得分:3)

解决此问题有两个单独的步骤。首先,我们必须查看每个函数的 time 复杂性,然后查看输出复杂性。

时间复杂度

由于g是自包含的,因此请先查看它。

g中完成的工作包括:

  • x^2执行循环
  • 使用参数x - 1
  • 的递归调用

因此可以将时间复杂度递归关系写为(使用大写将其与原始函数区分开来)

enter image description here

要解决它,反复自我替代以给出总和。这是从6到x的自然数的平方和:

enter image description here

在最后一步中,我们使用了标准结果。因此,a是常数:

  

enter image description here

接下来,f

  • 拨打g(x)
  • 使用参数x / 2
  • 进行一次递归调用
  • 一些不断的工作量

enter image description here

使用类似的方法:

enter image description here

应用停止条件:

enter image description here

因此:

enter image description here

由于指数期限2^(-x^3)消失了:

  

enter image description here

输出复杂性

这与上面的过程基本相同,递归关系略有不同。我将跳过细节并仅说明结果(使用小写输出函数):

enter image description here

因此f(g(n)) + g(f(n))的最终时间复杂度为:

  

enter image description here

     

哪个与您的来源给出的结果相符。