【问题标题】:Recursive Pascal's Triangle Row big O cost递归帕斯卡三角行大 O 成本
【发布时间】:2014-09-10 00:16:56
【问题描述】:

我正在为 CS 面试而学习,我决定尝试自己解决问题并递归解决。

我要解决的问题是:我希望能够编写一个递归函数来找到帕斯卡三角形的第 n 行。

Ex pascals(1) -> 1
   pascals(2) -> 1,1
   pascals(3) -> 1,2,1

我相信我已经解决了这个功能。它需要一个辅助函数才能从基本案例开始。

function int[] nthPascal(int[] a, int n){
  // in the case that the row has been reached return the completed array
  if(n==1){
    return a;
  }
  // each new row of pascal's triangle is 1 element larger. Ex 1, 11, 121,1331 etc. 
  int[] newA = new int[a.length()+1];

  //set the ends. Technically this will always be 1.
  // I thought it looked cleaner to do it this way. 
  newA[0]=a[0];

  newA[newA.length-1]=a[a.length-1];

  //so I loop through the new array and add the elements to find the value.
  //ex 1,1 -> -,2,- The ends of the array are already filled above
  for(int i=1; i<a.length; i++){

    // ex 1+1 = 2 for 1,1 -> 1,2,1
    newA[i]=a[i-1]+a[i]
  }
  //call the recursive function if we are not at the desired level
  return nthPascal(newA,n-1);
}

/**
*The helper function
*/
public int[] helperPascal(int n){
  return nthPascal(int[] {1},n);
}

我的问题是如何找到 bigO 成本?

我熟悉常见的算法成本以及如何找到它们。这中的递归让我感到困惑。

我知道它显然不是常数,n、nlogn 等。我的想法是它是 3^n?

我搜索了一个例子,发现: Pascal's Triangle Row SequenceWhat is the runtime of this algorithm? (Recursive Pascal's triangle)。 但我相信他们正试图在给定位置找到特定元素。我找不到任何人以这种方式实现帕斯卡三角形并谈论 bigO 成本。

这是因为有更好的方法来编写递归行查找 pascal 函数吗?如果是,请分享:)

【问题讨论】:

  • 1) nthFib 是什么? 2) 帮助函数的正确语法是return nthPascal(new int[] {1}, n); 3) 在Java 中,在计算数组长度时不要使用()(但你需要它来计算字符串的长度)。 4) intA 应该用new int[...] 声明,而不是int [...]。我知道这些都与您的问题无关。
  • 1) 哦,对不起,我的意思是 nthPascal 我先做 nthFibonaci。哦,谢谢你的java帮助。自从我用 java 编码以来已经有一段时间了,我正在练习没有和 ide

标签: java algorithm recursion big-o


【解决方案1】:

每次调用nthPascal,它只会递归调用自己一次。因此,您可以通过将函数的每次调用(不包括递归调用)的时间复杂度相加来获得时间复杂度。 (如果你有一个遍历二叉树的函数,它通常会递归调用自己两次,这使得计算更加复杂。不过,由于它只调用一次,所以计算非常简单。)

函数的每次调用都有一个循环执行a.length次,循环体以恒定时间执行。除了分配数组intA 时,没有任何其他循环或任何其他语句在恒定时间内执行,因为Java 将初始化数组的每个元素。但是,结果是,当您使用长度为 M 的数组调用 nthPascal 时,执行时间将为 O(M),不包括递归调用。

所以假设某个常数 k 的执行时间大约是 M*k,这意味着总执行时间将是 1*k + 2*k + 3*k + ... + (n-1)*k .而 1 + 2 + 3 + ... + n - 1 是 (n * (n - 1)) / 2,即 O(n2)。所以 O(n2) 是您正在寻找的答案。

【讨论】:

  • 哦,谢谢。我做错了。我认为是因为每次我被绊倒时数组中的值的数量都是不同的。谢谢!
【解决方案2】:

对于每个递归调用,您正在执行大小为 k 的 for 循环,其中 k 是递归调用的深度(在深度 k 处,您有一个大小为 k 的数组)。

要获取深度 n 的完整行,请在深度 1、2、...、n 处调用 nthPascal

因此,您的总复杂度将为1+2+...+n=n(n+1)/2 = O(n²)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多