今天突然想温习一下Java的基础,想了想就写写杨辉三角吧
1、直接法,利用二维数组
1 import java.util.Scanner; 2 public class Second 3 { 4 public static void main(String[] args) { 5 // TODO Auto-generated method stub 6 Scanner in=new Scanner(System.in); 7 int n=in.nextInt(); 8 int[][] Arr = new int[n][]; 9 in.close(); 10 for(int i = 0; i < Arr.length; i++) 11 { 12 Arr[i] = new int[i + 1]; 13 Arr[i][0] = 1; 14 Arr[i][i] = 1; 15 for(int j = 0; j < Arr[i].length - 1; j++) 16 if(j >= 1 && i > 1) 17 Arr[i][j] = Arr[i - 1][j - 1] + Arr[i - 1][j]; 18 } 19 for(int i = 0; i < Arr.length; i++) 20 { 21 for(int j = 0; j < Arr.length - Arr[i].length; j++) 22 System.out.print(" "); 23 for(int j = 0; j < Arr[i].length; j++) 24 { 25 System.out.print(Arr[i][j]); 26 System.out.print(" "); 27 } 28 System.out.println(); 29 } 30 } 31 }
2、使用递归方式
1 public class Second 2 { 3 public static int assign(int x,int y) 4 { 5 int z; 6 if(y==1||y==x) 7 return 1; 8 z=assign(x-1,y-1)+assign(x-1,y); 9 return z; 10 } 11 public static void main(String args[]) 12 { 13 for (int i=1; i<=5; i++) 14 { 15 for (int j=1; j<5-i+1; j++) 16 System.out.print(" ");//打印空格 17 for(int j=1;j<=i;j++) 18 System.out.print(assign(i,j)+" "); 19 System.out.println(); 20 } 21 } 22 }
作者:耑新新,发布于 博客园
转载请注明出处,欢迎邮件交流:zhuanxinxin@aliyun.com