杨辉三角形

题目:打印出杨辉三角形(根据输入n打印出n行如下图)
把三角行先去空成这样     

1   
11   
121   
1331   
14641     
…………

import java.util.*;
public class Test{
    //用二维数组打印
    public void cal(int n){
        int[][] s = new int[n][n];
        //赋值
        for(int i=0;i<n;i++){
            //空格以零处理
            for(int j=0;j<n-i-1;j++){
                s[i][j]=0;
            }
            //数字
            for(int j=n-i-1;j<n;j++){
                if(j==n-i-i||j==n-1)
                s[i][j]=1;
                else
                s[i][j]=s[i-1][j]+s[i-1][j+1];
            }
        }
        //输出
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(s[i][j]==0)
                System.out.print("    ");
                else
                System.out.print(s[i][j]+"        ");
            }
            System.out.println();
        }
        
    }
    public static void main(String args[]){
        Scanner scan = new Scanner(System.in);
        System.out.print("input n: ");
        int n = scan.nextInt();
        new Test().cal(n);
    }
}
    /*----运行结果
    input n: 5
                    1
                1        1
            1        2        1
        1        3        3        1
    1        4        6        4        1
    */
原文地址:https://www.cnblogs.com/laoquans/p/2963352.html