Java经典编程题50道之三十三

打印出杨辉三角形(要求打印出10行如下图)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

public class Example33 {

    public static void main(String[] args) {
        yanghui(10);
    }

    public static void yanghui(int n) {
        int[][] a = new int[n][n];
        for (int i = 0; i < n; i++) {
            a[i][i] = 1;
            a[i][0] = 1;
        }
        for (int i = 2; i < n; i++) {
            for (int j = 1; j < i; j++) {
                a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
            }
        }
        for (int i = 0; i < n; i++) {
            for (int k = 0; k < 2 * (n - i) - 1; k++) {
                System.out.print(" ");
            }
            for (int j = 0; j <= i; j++) {
                System.out.print(a[i][j] + "   ");
            }
            System.out.println();
        }
    }
}

原文地址:https://www.cnblogs.com/qubo520/p/6955795.html