1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
...................
public class PrintYangHui {
public static void main(String[] args){
/**
* 比較兩個print方法會有新的發現哦
*/
print1(5);
print2(5);
}
/**
* 按照書本上面描述的三角圖計算的
* 給第一行和第二行賦值
* 按照規則第二行的“2”不知道是怎麼計算的,所以手動賦初始值
* @param line
*/
public static void print1(int line){
/**
* 用int二維數組存儲,第一維表示行數,第二維表示列數
*/
int[][] aa = new int[line][2*line+1];
for(int i = 0; i<line ;i++){
for(int j = 0;j< 2*line+1;j++){
if(i == 0){
if(j == line ){
aa[i][j] = 1;
}else{
aa[i][j] = 0;
}
}else if(i == 1){
if(j == line ){
aa[i][j] = 2;
}else if(j == line -2 || j == line +2 ){
aa[i][j] = 1;
}else{
aa[i][j] = 0;
}
}else{
if(j == 0){
aa[i][j] = aa[i-1][j+1];
}else if(j == 2*line){
aa[i][j] = aa[i-1][j-1];
}else{
aa[i][j] = aa[i-1][j-1] +aa[i-1][j+1];
}
}
/**
* 輸出時把所有的“0”都替換成空格
*/
if(aa[i][j] == 0){
System.out.print(" ");
}else{
System.out.print(aa[i][j]);
}
}
System.out.println("\n");
}
}
/**
* 按照楊輝三角的規則計算
* 只給予第一行賦值
* @param line
*/
public static void print2(int line){
int[][] aa = new int[line][2*line+1];
for(int i = 0; i<line ;i++){
for(int j = 0;j< 2*line+1;j++){
if(i == 0){
if(j == line ){
aa[i][j] = 1;
}else{
aa[i][j] = 0;
}
}else{
if(j == 0){
aa[i][j] = aa[i-1][j+1];
}else if(j == 2*line){
aa[i][j] = aa[i-1][j-1];
}else{
aa[i][j] = aa[i-1][j-1] +aa[i-1][j+1];
}
}
if(aa[i][j] == 0){
System.out.print(" ");
}else{
System.out.print(aa[i][j]);
}
}
System.out.println("\n");
}
}
}