输出宝塔型杨辉三角(Java语言)

题目要求:输出如下格式的杨辉三角,输入n,则输出前n行杨辉三角

《输出宝塔型杨辉三角(Java语言)》

算法思想:该题目不同于普通的杨辉三角的输出,一般,普通杨辉三角第一列的位置全部为1,对角线的位置全是1,其他位置等于正上方和左上方元素值的加和、该题的难点在于多了前面空格的输出。

参考代码如下:

import java.util.Scanner;

public class YangHui {
	
	public static void main(String[] args) {
		System.out.println("how many lines you want:");
		Scanner in = new Scanner(System.in);
		while(in.hasNext()){
			int n = in.nextInt();
			int[][] arr = new int[n][];    
			for(int i = 0; i < n; i++){
				arr[i] = new int[i + 1];       //行从0开始,列数加1   否则容易出现空指针异常
				for(int k = n - 1; k > i; k--){     //从第一行开始,依次给每行增加不同的空格
					System.out.print(" ");
				}
				
				for(int j = 0; j <= i; j++){
					if(j == 0 || j == i){    //两边的值
						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();
			}
		}
		in.close();
	}
}
    原文作者:杨辉三角问题
    原文地址: https://blog.csdn.net/when_less_is_more/article/details/78277984
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞