杨辉三角的排列性质:
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 10 45 120 210 252 210 120 45 10 1 1 11 55 165 330 462 462 330 165 55 11 1 1 12 66 220 495 792 924 792 495 220 66 12 1 1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1 1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1 1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1 1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
杨辉三角的特性:
1.每行开始和结束都为1
2.除首尾外每个数都为它上方两个数之和
3.第n行有n个数
4.每行有总行数-行数个空格,比如总够有10行,那么第3行就有10-3=7个空格
根据这些特性就可以用java来实现我们的杨辉三角了。
import java.util.*; class Demo { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("请输入行数:"); int line = in.nextInt(); int [][] arr = new int[line][]; //保证输出line行 for(int i=0;i<line;i++) { //行是从0开始 列长度为行加1,比如第一行有一个元素即arr[0]=new int[1]; arr[i] = new int[i+1]; //从第一行开始 依次给每行加总行数-行个空格 for(int k=1;k<line-i;k++){ System.out.print(" "); } //控制每行输出的元素 for(int j=0;j<=i;j++) { if(j==0 || j==i) { //如果是两边的值,就赋值1 arr[i][j]=1; System.out.print(arr[i][j]+" "); }else{ //如果是中间的值,就用上边两个数求出这个值 arr[i][j]=arr[i-1][j]+arr[i-1][j-1]; System.out.print(arr[i][j]+" "); } } System.out.println();//换行 } } }