楊輝三角性質:每行首尾為 1,內部數字等於上一行左右兩數之和。第 n 行(0-indexed)對應二項式係數 C(n, k)。
public class PascalTriangle {
public static void main(String[] args) {
int rows = 10;
int[][] triangle = new int[rows][];
for (int i = 0; i < rows; i++) {
triangle[i] = new int[i + 1];
triangle[i][0] = triangle[i][i] = 1; // 首尾為 1
for (int j = 1; j < i; j++) {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
}
// 列印置中對齊
for (int i = 0; i < rows; i++) {
// 前置空格
for (int s = 0; s < rows - i - 1; s++) System.out.print(" ");
for (int j = 0; j <= i; j++) {
System.out.printf("%4d", triangle[i][j]);
}
System.out.println();
}
}
}
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
int[] row = new int[rows];
for (int i = 0; i < rows; i++) {
row[i] = 1;
for (int j = i - 1; j > 0; j--) { // 逆向更新避免覆蓋
row[j] += row[j-1];
}
// 列印 row[0..i]
}
空間複雜度從 O(n²) 降為 O(n)。
利用組合數公式 C(n,k) = C(n,k-1) * (n-k+1) / k 逐行計算,無需儲存上一行。