杨辉三角

问题描述

杨辉三角形又称Pascal三角形,它的第i+1行是(a+b)i的展开式的系数。

它的一个重要性质是:三角形中的每个数字等于它两肩上的数字相加。

下面给出了杨辉三角形的前4行:

   1

  1 1

 1 2 1

1 3 3 1

给出n,输出它的前n行。

输入格式:

输入包含一个数n。

输出格式:输出杨辉三角形的前n行。每一行从这一行的第一个数开始依次输出,中间使用一个空格分隔。请不要在前面输出多余的空格。
样例输入
4
样例输出
1
1 1
1 2 1
1 3 3 1
数据规模与约定
1 <= n <= 34。
 

杨辉三角的源码【一维数组】:

 1 import java.util.Scanner;
 2 
 3 public class YangHui {
 4 
 5     public static void main(String[] args) {
 6         int i = 1;
 7         Scanner mScanner = new Scanner(System.in);
 8         int n = mScanner.nextInt();
 9         int yh[] = new int[n];
10         for (i = 0; i < yh.length; i++) {
11             yh[i] = 1;
12             for (int j = i - 1; j > 0; j--) {
13                 yh[j] = yh[j - 1] + yh[j];
14             }
15             for (int j = 0; j <= i; j++) {
16                 System.out.print(yh[j] + "	");
17             }
18             System.out.println();
19         }
20     }
21 
22 }

 杨辉三角的源码【二维数组】:

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         Scanner mScanner = new Scanner(System.in);
 8         int n = mScanner.nextInt();
 9         Yang(n);
10     }
11 
12     public static void Yang(int m) {
13         int max = 40;
14         int[][] arr = new int[max][max];
15         arr[0][0] = 1;
16         for (int i = 0; i < m; i++) {
17             arr[i][0] = arr[i][i] = 1;
18             for (int j = 1; j <= i    ; j++) {
19                  arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];  
20             }
21         }
22 
23         for(int i = 0;i < m;i++){  
24             for(int j = 0;j <= i;j++){  
25                 System.out.print(arr[i][j]+" ");
26             }  
27             System.out.println();
28         }  
29 
30     }
31 }

-

原文地址:https://www.cnblogs.com/zhjsll/p/4374484.html