楊輝三角的規(guī)律:
1洪灯、第n行有n個(gè)數(shù)字.
2世囊、每一行的開始和結(jié)尾數(shù)字都為1哭廉。(用二維數(shù)組表示就是a[i][0]=1; a[i][j]=1(當(dāng)i==j時(shí)))
3战虏、第n+1行的第i個(gè)數(shù)字等于第n行的i-1個(gè)數(shù)字加上第n行的i個(gè)數(shù)字萍丐。(用二維數(shù)組表示就是 a[i+1][j]=a[i][j-1]+a[i][j];)
方法一:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int [][] a = new int [n][n];
for(int i = 0;i < a.length;i++) {
for(int j = 0;j <= i;j++) {
if(j == 0 || j == i) {
a[i][j] = 1;
}
else {
a[i][j] = a[i-1][j-1] + a[i-1][j];
}
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
方法二:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] a = new int[n][];
for(int i=0;i<a.length;i++) {
a[i] = new int[i + 1];
}
for(int i = 0;i < a.length;i++) {
for(int j = 0;j < a[i].length;j++) {
if(j == 0 || i == j) {
a[i][j]=1;
}else {
a[i][j]=a[i-1][j]+a[i-1][j-1];
}
}
}
for(int i = 0;i < a.length;i++) {
for(int j = 0;j < a[i].length;j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
}
方法三:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
int number = 1;
System.out.format("%" + (n - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}