【问题标题】:Big O notation of recursive functions递归函数的大 O 表示法
【发布时间】:2016-11-30 00:48:34
【问题描述】:

我一直在练习大 O 表示法,我似乎理解它,除了递归函数。我可以处理简单的问题(比如O(n)O(1),但其他任何事情我通常都会迷路。 以下是三个练习题,如果有人解释他们如何找到答案的过程,我将不胜感激。

  public static int method2(int n)
  {
    if (n < 1) throw new IllegalArgumentException();
    if (n == 1)
      return 2;
    else
      return method2(n - 1) * (2 * n);
  }


  public static void method3(int n)
  {
    if (n < 1) throw new IllegalArgumentException();
    if (n == 1)
      System.out.print("1");
    else {
      method3(n - 1);
      System.out.print(", " + n);
    }
  }


  public static void method4(int n)
  {
    if (n < 1) throw new IllegalArgumentException();
    if (n==1) System.out.print(1);
    else if (n==2) System.out.print("1 1");
    else {
        System.out.print((n+1)/2+ " ");
        method4(n-2);
        System.out.print(" "+(n+1)/2);
    }
}
}

【问题讨论】:

  • 想想问题是如何随着每次递归调用而缩小的。例如,如果它是线性收缩的,并且每次递归只有一次调用,那么它将是 O(n)。如果每个调用创建两个新调用并且它们都线性收缩,那么它将是 O(n^2)。

标签: time big-o complexity-theory notation


【解决方案1】:

这个例子很简单。

method2 中,您从n 开始,然后通过1 向下直到到达1。所以你会收到nmethod2 电话,那就是O(n)

method3method2 相同,只是操作不同。您通过将n 减少1 来调用method3 直到其1。

method4 中,您将n 减少2,直到其12,因此您将执行n/2 步骤,这仍然是O(n)。

这并不是理解递归函数速度的最佳示例。您需要使用具有多个递归选项的示例。

所有这些选项都可以转换为具有相同复杂性的 for 循环,因此如果可以帮助您,请尝试以这种方式思考。

【讨论】: