/*
打印出楊輝三角。取(x+y)的9次冪,10行。
*/
import java.util.Arrays;
class Demo
{
private Demo(){}
private static Demo instance = new Demo();
public static Demo getInstance()
{
return instance;
}
public int[][] getTriangle(int n)
{
int[][] arr = new int[n+1][2*n+1];
Arrays.fill(arr[0], 0);
arr[0][n] = 1;
for(int i = 1; i < n+1; i++)
{
for(int j = 0; j < 2*n+1; j++)
{
if(j == 0)
{
arr[i][j] = arr[i-1][j+1];
}
else if(j == 2*n)
{
arr[i][j] = arr[i-1][j-1];
}
else
arr[i][j] = arr[i-1][j-1] + arr[i-1][j+1];
}
}
return arr;
}
public void printTriangle(int[][] arr, int n)
{
for(int i = 0; i < n+1 ;i++)
{
for(int j = 0; j < 2*n+1; j++)
{
if(arr[i][j] == 0)
System.out.print(" " + " ");
else
System.out.print(arr[i][j] + " ");
}
System.out.println("");
}
}
}
class MainClass
{
public static void main(String[] args) throws Exception
{
Demo d = Demo.getInstance();
int[][] a = d.getTriangle(6);
d.printTriangle(a, 6);
// System.out.println("輸入一個1到9的數字和重複次數,用空白符分隔:");
}
}
/*
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
0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 0 1 0 0 0 0 0
0 0 0 0 1 0 2 0 1 0 0 0 0
0 0 0 1 0 3 0 3 0 1 0 0 0
0 0 1 0 4 0 6 0 4 0 1 0 0
0 1 0 5 0 10 0 10 0 5 0 1 0
1 0 6 0 15 0 20 0 15 0 6 0 1
......................................................
楊輝三角最本質的特徵是,它的兩條斜邊都是由數字1組成的,而其餘的數則是等於它肩上的兩個數之和。
上面是(x+y)的6次方。
n次方中間有n-1個數,首尾兩端都是1,一共有2n+1個元素,n+1行。
最後一個元素是arr[n][2n],第一行的最中間的元素腳標是arr[0][n]
第一個元素和最後一個元素直接等於上一行的斜線值。
折磨啊。
*/
猶如木偶