直接代码走起:
/**
* 巴斯卡(Pascal)三角形(杨辉三角)
* @author idea-pcfff
*
*/
public class Pascal {
/**
* 运用公式,迭代计算
* nCr = [(n-r+1)*nCr-1]/r
nC0 = 1
* @param n 行row
* @param r 列 column
* @return 值
*/
private static long combi(int n, int r){
int i;
long p = 1;
for(i = 1; i <= r; i++){
p = p * (n-i+1) / i;
}
return p;
}
public static void draw(final int N){
int n, r, t;
StringBuffer sb = null;
for(n = 0; n <= N; n++) {
int count = N*2-n;
sb = new StringBuffer();
for(int i = 0;i<count;i++){
sb.append(" ");
}
System.out.print(sb);
for(r = 0; r <= n; r++){
System.out.print( " " + combi(n, r) + " ");
}
System.out.println();
}
}
/**
* 使用二维数组输出杨辉三角,全部输出
* @param arr 输出指定行列的杨辉三角 ,要求行列相同
*/
public static void draw(int[][] arr){
arr[0][0] = 1;
int n,r ,N= arr.length;
StringBuffer sb = null;
for(n=0;n<N;n++){
int count = N*2-n;
sb = new StringBuffer();
for(int i = 0;i<count;i++){
sb.append(" ");
}
System.out.print(sb);
for(r=0;r<=n;r++){
if(r == n || r == 0){
arr[n][r] = 1;
}else{
arr[n][r] = arr[n-1][r-1]+arr[n-1][r];
}
System.out.print( " " + arr[n][r] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
//draw(5);
int[][] a = new int[10][10];
draw(a);
}
}