1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
上面的圖形熟悉嗎?它就是咱們中學時候學過的楊輝三角。java
輸入數據包含多組測試數據。
每組測試數據的輸入只有一個正整數n(1≤n≤128),表示將要輸出的楊輝三角的層數。
輸入以0結束算法
對應於每個輸入,請輸出相應層數的楊輝三角,每一層的整數之間用一個空格隔開,每個楊輝三角後面加一個空行。數組
2 3 0
1 1 1 1 1 1 1 2 1
假設楊輝三角的使用一個二維數組a進行表示。a[i][j]表示第i+1行第j+1列元素的值,有公式:app
a[i][j]={1a[i−1][j−1]+a[i−1][j]j=0 or j=i0<j<i測試
將楊輝三角使用一個一維數組a表示,從下標0開始,楊輝三角第i行第j列個元素對應用到數組a的下標爲x(i,j):則ui
x(i,j)=(∑k=1i−1k)+j−1 (j≥1 and i≥j)spa
x(i,j)=i(i−1)2+j−1.net
得code
a[x(i,j)]={1a[x(i−1,j−1)][x(i−1,j)]j=1 or j=i1<j<i圖片
import java.math.BigInteger; import java.util.Scanner; /** * Declaration: All Rights Reserved !!! */ public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt")); while (scanner.hasNext()) { int num = scanner.nextInt(); if (num == 0) { break; } System.out.println(triangle2(num)); } scanner.close(); } /** * 【解法一】 * 計算楊輝三角 * * @param n 楊輝三角的行數 * @return 楊輝三角 */ private static String triangle(int n) { if (n < 1) { throw new IllegalArgumentException("參數必須是正整數"); } if (n == 1) { return "1\n"; } else if (n == 2) { return "1\n1 1\n"; } StringBuilder b = new StringBuilder(); BigInteger[][] t = new BigInteger[n][n]; for (int i = 0; i < t.length; i++) { t[i] = new BigInteger[n]; } for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { if (j == 0 || i == j) { t[i][j] = new BigInteger("1"); } else { t[i][j] = t[i - 1][j - 1].add(t[i - 1][j]); } b.append(t[i][j]).append(' '); } b.setCharAt(b.length() - 1, '\n'); } return b.toString(); } /** * 【解法二】 * 計算楊輝三角 * * @param n 楊輝三角的行數 * @return 楊輝三角 */ private static String triangle2(int n) { if (n < 1) { throw new IllegalArgumentException("參數必須是正整數"); } BigInteger[] t = new BigInteger[n * (n + 1) / 2]; StringBuilder b = new StringBuilder(); for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { // 第i行第一個元素的下標是: (i - 1) * i / 2 // 第i行第j個元素的下標是:(i - 1) * i / 2 + j - 1 int idx = (i - 1) * i / 2 + j - 1; if (j == 1 || i == j) { t[idx] = BigInteger.ONE; } else { // 第i-1行第一個元素的下標是: (i - 2) * (i - 1) / 2 int x = (i - 2) * (i - 1) / 2 + j - 1; int y = (i - 2) * (i - 1) / 2 + j - 2; t[idx] = t[x].add(t[y]); } b.append(t[idx].toString()).append(' '); } b.setCharAt(b.length() - 1, '\n'); } return b.toString(); } }