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
代码:
输出结果:
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
相关文章推荐
- Java经典算法40例(六)
- Java经典算法40例(十一)
- Java经典算法40例(二十)
- java的经典算法40例-全源码
- Java经典算法40例(二十七)
- Java经典算法40例(三十七)
- Java经典算法40例(二十八)
- Java经典算法40例(三十一)
- Java经典算法40例(三十八)
- Java经典算法40例(十二)
- Java经典算法40例(三十二)
- Java经典算法40例(三十九)
- JAVA经典算法40例
- Java经典算法40例(二十九)
- Java经典算法40例(三)
- Java经典算法40例(四十)
- Java经典算法40例(十四)
- Java经典算法40例(十五)
- Java经典算法40例(三十四)
- JAVA经典算法40例