打印输出 杨辉三角

33 【程序 33 杨辉三角 】
题目:打印出杨辉三角形(要求打印出 10 行如下图)
程序分析:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

//可以看出 ,1.杨辉三角每一层的元素个数等于层数 2.每一层首尾元素的数值为1   3.每一层索引从1开始元素值=上一层对应索引值+上一层对应索引值的前一个

//即 array[i][j]=array[i-1][[j]+array[i-1][j-1];


 1 public static void function01() {
 2         int[][] array = new int[10][10];// 先定义一个10×10的数组
 3         // 按照三角形的走势,定义每行的空间长度 lenth
 4         for (int i = 0; i < array.length; i++) {
 5             // 重新定义每行对应的长度
 6             array[i] = new int[i + 1];
 7         }
 8 
 9         for (int i = 0; i < array.length; i++) {
10             // 首尾值为1
11             array[i][0] = 1;
12             array[i][i] = 1;
13             // 根据规律赋值
14             for (int j = 1; j < i; j++) {// 索引从1开始而不是0
15                 array[i][j] = array[i - 1][j] + array[i - 1][j - 1];
16             }
17         }
18         // 把数组的元素按照一定形状打印出来
19 
20         for (int j = 0; j < array.length; j++) {
21             // 打印空格
22             // 受数字位数的影响,可能后面行的元素不对齐
23             for (int i = array.length; i > j; i--) {
24                 System.out.print(" ");
25             }
26             for (int j2 = 0; j2 < array[j].length; j2++) {
27 
28                 System.out.print(array[j][j2] + " ");
29             }
30             System.out.println();
31         }
32 
33     }


 
 1           1 
 2          1 1 
 3         1 2 1 
 4        1 3 3 1 
 5       1 4 6 4 1 
 6      1 5 10 10 5 1 
 7     1 6 15 20 15 6 1 
 8    1 7 21 35 35 21 7 1 
 9   1 8 28 56 70 56 28 8 1 
10  1 9 36 84 126 126 84 36 9 1

受数字位数影响,后面的排列不是很整齐,但是前6行大致上比较整齐的

原文地址:https://www.cnblogs.com/doudou2018/p/9459902.html