1. 程式人生 > >陣列經典應用之—楊輝三角

陣列經典應用之—楊輝三角

/**
* 經典楊輝三角
*  1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
* @author 378375
*/
//1.初始化10行陣列
int[][] yangHui = new int[10][];
//2.初始化列數
for (int i = 0; i < yangHui.length; i++) {
yangHui[i] = new int[i+1];
}
//3.給二維陣列的第一列和最後一列賦值為:1
for (int i = 0; i < yangHui.length; i++) {
yangHui[i][0] = yangHui[i][i] = 1;
}
//4.根據規律賦值三角內部相應元素賦值
for (int i = 0; i < yangHui.length; i++) {
for (int j = 0; j < yangHui[i].length; j++) {
if(i > 1 && j > 0 && i > j){
yangHui[i][j] = yangHui[i-1][j] + yangHui[i-1][j-1];
}
}
}

//5.遍歷
for (int i = 0; i < yangHui.length; i++) {
for (int j = 0; j < yangHui[i].length; j++) {
System.out.print(yangHui[i][j]+" ");

}
System.out.println();
}