/*
打印出杨辉三角。取(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]
第一个元素和最后一个元素直接等于上一行的斜线值。
折磨啊。
*/
犹如木偶