英文:
Can I do a quicker recursion for this pascal triangle in java?
问题
public static int[] computePT(int k) {
int[] arr = new int[k];
if (k == 1) {
arr[0] = 1;
return arr;
} else {
arr[0] = 1;
int prev = 1;
for (int i = 1; i <= (k+1)/2 - 1; i++) {
int current = prev * (k - i + 1) / i;
arr[i] = current;
arr[k - i] = current;
prev = current;
}
return arr;
}
}
(Note: The code you provided has an issue with the for loop condition. The condition should be i <= (k+1)/2 - 1
instead of i >= 0
in order to correctly generate the elements of the kth row of Pascal's triangle.)
英文:
public static int[] computePT(int k) {
int[] arr = new int[k];
if(k==1){
arr[0] = 1;
return arr;
}else{
for (int i=(k+1)/2 -1 ; i >= 0; i--){
if(i==0){
arr[0] = 1;
arr[k-1] = 1;
}else {
int[] yell = computePT(k-1);
arr[i] = yell[i-1] + yell[i];
arr[k-i-1] = arr[i];
}
}
return arr;
}
}
This function will return the elements of kth row in a pascal triangle, but I would like to do this in a shorter runtime. It seems that the recursion is not fast enough...
答案1
得分: 0
你计算
int[] yell = computePT(k-1);
循环内。将它移到循环之前应该会提升性能。
英文:
You compute
int[] yell = computePT(k-1);
int the loop. Moving it before the loop should make a better performance
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论