用java二維數組實現楊輝三角
這是之前做的,想保留下來
1 class Triangles{ public Triangles(){} 2 3 public static void Pascal(int n) { 4 int[][] a=new int[n][]; 5 for(int i=0;i<n;i++) { 6 a[i]=new int[i+1]; //動態分配二維數組空間 7 } 8 for(int i=0;i<n;i++) { 9 a[i][0]=1; //用一次循環解決邊上及中間元素的賦值 10 a[i][i]=1; 11 for(int j=1;j<i;j++) { //通過行和列的關系,內層j<i是個很巧妙的寫法 12 a[i][j]=a[i-1][j]+a[i-1][j-1]; 13 } 14 } 15 16 for(int i=0;i<n;i++) { 17 for(int j=0;j<=i;j++) { 18 System.out.print(a[i][j]+" "); 19 } 20 System.out.println(); 21 } 22 } 23 } 24 25 public class Triangle { public static void main(String[] args) { 26 27 Triangles.Pascal(10); 28 } 29 }