您的位置:首页 > 编程语言 > Java开发

Java经典算法40例(三十三)

2017-07-16 13:25 302 查看
题目:打印出杨辉三角形(要求打印出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

;
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: