题目:打印出杨辉三角形(要求打印出10行如下图)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
代码:
/**
* 杨辉三角
* @author cheng
*
*/
public class ThirtyThree {
public void yanghuisanjiao(int n){
int[][] a=new int[n][n];
a[0][0]=1;
for(int i=1;i<n;i++){
a[i][0]=1;
a[i][i]=1;
}
for(int i=2;i<n;i++){
for(int j=1;j<i;j++){
a[i][j]=a[i-1][j]+a[i-1][j-1];
}
}
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
ThirtyThree thirtyThree=new ThirtyThree();
thirtyThree.yanghuisanjiao(10);
}
}
输出结果:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1