1233: 輸出楊輝三角前n行(Java)


WUSTOJ 1233: 輸出楊輝三角前n行

題目

原題鏈接

Description

       輸出楊輝三角前n行。

Input

       輸入一個數n(n <= 9)

Output

       輸出楊輝三角前n行。(注意行末不能有多余的空格,數字以%3d的格式輸出)

Sample Input

3
4

Sample Output

      1
    1   1
  1   2   1

        1
      1   1
    1   2   1
  1   3   3   1

分析

  • 考慮到多組輸入,用二維數組提前初始化,再按照格式輸出比較快,循環里面都每次單獨計算的話可能較慢(未測試)
  • 楊輝三角原理
    第1列和對角線全部都是1。其他位置的數是它上面的1個數以及左上的1個數。公式如下:
 a[i][j] = a[i - 1][j - 1] + a[i - 1][j]

楊輝三角5層

注意

  • 前面的空格每次加2個,不是1個
  • 每2個數之間有1個空格
  • 每個數占3格,用%3d控制格式
  • 末尾沒有空格
  • 每組數據輸出之后有1個空行

代碼

import java.util.Scanner;

public class Main {

	private Scanner sc;
	private int n;
	// 保存楊輝三角,下標從0開始
	private int[][] yangHui;
	
	public Main() {
		sc = new Scanner(System.in);
		init();		// 初始化
		while(sc.hasNext()) {
			n = sc.nextInt();
			display();		// 打印
			System.out.println();	// 每組數據末尾換行
		}
		sc.close();
	}
	
	/** * 初始化楊輝三角數組 */
	private void init() {
		yangHui = new int[9][9];
		yangHui[0][0] = 1;
		int i, j;
		for(i = 1; i < 9; i++) {
			yangHui[i][0] = yangHui[i][i] = 1;	// 第1列和最后1列
			for(j = 1; j < i; j++) {
				yangHui[i][j] = yangHui[i - 1][j - 1] + yangHui[i - 1][j];
			}
		}
	}
	
	/** * 打印楊輝三角 */
	private void display() {
		int i, j;
		for(i = 0; i < n; i++) {
			// 前面空格個數
			for(j = n - i - 1; j > 0; j--) {
				System.out.print(" ");
			}
			// 每個數占3格,且每個數之間空1格
			for(j = 0; j < i; j++) {
				System.out.printf("%3d ", yangHui[i][j]);
			}
			// 最后1個數,換行
			System.out.printf("%3d\n", yangHui[i][j]);
		}		
	}

	public static void main(String[] args) {
		new Main();
	}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM