Search code examples
javaarraysrecursionpascals-triangle

Print Pascal's Triangle using recursion


I'm trying to develop a program that prints out Pascal's Triangle using recursion. Here are my codes:

public class PascalTriangle {
    public static int[] computePT(int k) {
        int[] pt = new int[k + 1];
        if (k == 0) {
            pt[0] = 1;
            return pt;
        } else {
            int[] ppt = computePT(k - 1);
            pt[0] = pt[k] = 1;
            for (int i = 1; i < ppt.length; i++) {
                pt[i] = ppt[i - 1] + ppt[i];
            }
        }
        return pt;
    }
}
public class PascalTriangleDriver {
    public static void main(String args[]) {
        int k = 10;

        int arr[] = PascalTriangle.computePT(k);

        for (int i = 0; i < arr.length; i++)
            System.out.print(arr[i] + " ");

        System.out.println();
    }
}

The code runs perfectly, however my issue is that I want to modify my PascalTriangle code (not the PascalTriangleDriver code) such that when k=10, for example, it prints out:

1 9 36 84 126 126 84 36 9 1

instead of:

1 10 45 120 210 252 210 120 45 10 1

Solution

  • You seem to have made an off-by-1 error. One simple way to solve this is to write another method that calls your original method with k-1:

    // this is your original method, just renamed:
    private static int[] computePTImpl(int k) {
        int[] pt = new int[k + 1];
        if (k == 0) {
            pt[0] = 1;
            return pt;
        } else {
            int[] ppt = computePT(k - 1);
            pt[0] = pt[k] = 1;
            for (int i = 1; i < ppt.length; i++) {
                pt[i] = ppt[i - 1] + ppt[i];
            }
        }
        return pt;
    }
    
    // you will call this method:
    public static int[] computePT(int k) {
        return computePT(k - 1);
    }
    

    Alternatively, you can actually fix your code by replacing ks with k-1s:

    public static int[] computePT(int k) {
        int[] pt = new int[k]; // note the change
        if (k == 1) { // note the change
            pt[0] = 1;
            return pt;
        } else {
            int[] ppt = computePT(k - 1);
            pt[0] = pt[k - 1] = 1; // note the change
            for (int i = 1; i < ppt.length; i++) {
                pt[i] = ppt[i - 1] + ppt[i];
            }
        }
        return pt;
    }
    

    Note that we don't change the recursive call because if we did, we would be saying that the k-th row of Pascal's triangle depends on the k-2-th row, which is not true.