我可以为这个 Java 中的 Pascal 三角形实现更快的递归吗?

huangapple go评论80阅读模式
英文:

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 &gt;= 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

huangapple
  • 本文由 发表于 2020年5月4日 21:05:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/61592897.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定