Skip to content
thesarfo

Reference

Pascal's Triangle

Three related problems — the element at a given row/column, printing a single row, and printing the whole triangle — all without recomputing from scratch.

views 0

Each row starts/ends with 1; each internal value is the sum of the two values above it.

1. Element at a Given Row/Column

Equivalent to the binomial coefficient C(row-1, col-1), computable iteratively without factorials:

public static int getElement(int row, int col) {
row = row - 1;
col = col - 1;
long element = 1;
for (int i = 0; i < col; i++) {
element = element * (row - i) / (i + 1);
}
return (int) element;
}

2. Print the Nth Row

Each element derives from the previous one: next = previous * (row - col) / col.

public static List<Integer> generateRow(int row) {
List<Integer> result = new ArrayList<>();
long element = 1;
result.add((int) element);
for (int col = 1; col < row; col++) {
element = element * (row - col) / col;
result.add((int) element);
}
return result;
}

For row = 5: [1, 4, 6, 4, 1].

3. Print the Whole Triangle up to N Rows

Just call generateRow for each row 1..N.

public static List<List<Integer>> generatePascalTriangle(int n) {
List<List<Integer>> pascalTriangle = new ArrayList<>();
for (int i = 1; i <= n; i++) {
pascalTriangle.add(generateRow(i));
}
return pascalTriangle;
}