Java 递归Pascal';s三角行大O成本
我正在为CS面试而学习,我决定试着编出自己的问题,然后递归地解决它 我试图解决的问题是:我希望能够编写一个递归函数,找到pascal三角形的第n行Java 递归Pascal';s三角行大O成本,java,algorithm,recursion,big-o,Java,Algorithm,Recursion,Big O,我正在为CS面试而学习,我决定试着编出自己的问题,然后递归地解决它 我试图解决的问题是:我希望能够编写一个递归函数,找到pascal三角形的第n行 Ex pascals(1) -> 1 pascals(2) -> 1,1 pascals(3) -> 1,2,1 我相信我已经解决了这个函数。它需要一个helper函数来启动基本用例 function int[] nthPascal(int[] a, int n){ // in the case that the
Ex pascals(1) -> 1
pascals(2) -> 1,1
pascals(3) -> 1,2,1
我相信我已经解决了这个函数。它需要一个helper函数来启动基本用例
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);
}
函数int[]nthPascal(int[]a,int-n){
//如果已到达该行,则返回已完成的数组
如果(n==1){
返回a;
}
//帕斯卡三角形的每一新行大1个元素。例如1、11、1211331等。
int[]newA=newint[a.length()+1];
//设置端点。从技术上讲,这将始终是1。
//我觉得这样做看起来更干净。
newA[0]=a[0];
newA[newA.length-1]=a[a.length-1];
//因此,我循环遍历新数组并添加元素以查找值。
//ex1,1->-,2,-上面已经填充了数组的末端
对于(int i=1;i
及
.
但他们试图在给定的位置找到一个特定的元素,我相信。我找不到任何人用这种方式实现pascal三角形,并谈论bigO成本
这是因为有更好的方法来编写递归行查找pascal函数吗?如果是这样,请分享:)对于每个递归调用,您正在执行大小为k
的For循环,其中k
是递归调用的深度(在深度k
处,您有一个大小为k
的数组)
要获取深度n
处的完整行,请在深度1、2、…、n处调用nthPascal
因此,您的总复杂度将是1+2+…+n=n(n+1)/2=O(n²)
每次调用nthPascal
,它只递归调用自己一次。因此,您可以通过添加函数每次调用的时间复杂度(不包括递归调用)来获得时间复杂度。(如果您有一个遍历二叉树的函数,它通常会递归调用自身两次,这使得计算更加复杂。不过,在这里,由于它只调用自身一次,因此计算非常简单。)
函数的每次调用都有一个循环,它执行a.length
次,循环体以固定时间执行。除了在分配数组intA
时,没有任何其他循环或任何其他语句以固定时间执行,因为Java将初始化数组的每个元素y、 但是,结果是,当您使用长度为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)是您要寻找的答案。1)什么是nthFib
?2)helper函数的正确语法是return nthPascal(new int[]{1},n);
3)在Java中,在计算数组长度时不要使用()
(但字符串长度需要它)。4)intA
应该用new int[…]
声明,而不是int[…]
。我意识到这些都与你的问题无关。1)哦,对不起,我的意思是nthPascal,我是先做nthFibonaci的。哦,谢谢你的java帮助。我已经有一段时间没有用java编写代码了,我正在练习不用Ideo和Ideo来做。谢谢你。我做错了。我想是因为数组中的值的数量太多了每次我被绊倒都不一样。谢谢!