Pascal's Triangle
Problem
Read n and print the first n rows of Pascal's triangle. Each row starts and ends with 1. Every other number is the sum of the two numbers above it. Print the numbers of a row separated by one space.
Constraints
- 1 <= n <= 20
Examples
Input
3
Output
1 1 1 1 2 1
Solutions
We fill each row with 1, then replace the middle values with the sum of two values from the previous row. This is a small example of dynamic programming: we reuse an earlier result.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).
/*
* Problem : First rows of Pascal's triangle.
* Input : One integer n (rows).
* Output : n lines of numbers.
* Approach: Build each row from the previous row.
* Time : O(n^2)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int rows = new Scanner(System.in).nextInt();
// Step 1: Keep the previous row. The first row has no previous row, so we start with an empty array.
int[] previous = new int[0];
// Step 2: Repeat once for each row. Row numbers go from 1 to rows.
for (int row = 1; row <= rows; row++) {
// Step 3: Row i has i numbers. The first and last number are always 1.
int[] current = new int[row];
current[0] = 1;
current[row - 1] = 1;
// Step 4: Each middle number is the sum of the two numbers above it.
for (int position = 1; position < row - 1; position++) {
current[position] = previous[position - 1] + previous[position];
}
// Step 5: Print the row with one space between numbers.
StringBuilder line = new StringBuilder();
for (int position = 0; position < row; position++) {
if (position > 0) {
line.append(" ");
}
line.append(current[position]);
}
System.out.println(line);
// Step 6: The current row becomes the previous row for the next loop.
previous = current;
}
}
}
Hints (2)
- Look at the numbers above each middle number.
- Save the previous row in a variable.