【发布时间】: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 Sequence 和 What 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