Lanqiao Cup Test Questions-Basic Practice Yang Hui Triangle

Resource Limitation
Time Limitation: 1.0s
Memory Limitation: 256.0MB
Problem Description
Yang Hui's triangle is also called Pascal's triangle, and its i+ 1th row is the coefficient of the expansion of (a+b)i.

One of its important properties is that each number in the triangle is equal to the sum of the numbers on its two shoulders.

The first 4 rows of Yang Hui's triangle are given below:

1
1 1
1 2 1
1 3 3 1
Given n, output its first n rows.

Input format The
input contains a number n.
Output format
Output the first n rows of Yanghui triangle. Each line is output in sequence starting from the first number of this line, separated by a space in the middle. Please do not output extra spaces in front.

Sample input 4
Sample output
1
1 1
1 2 1
1 3 3 1

Data size and convention 1 <= n <= 34.

import java.util.Scanner;
public class Main {
    
    
	public static void main(String[] args) {
    
    
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int[][] a = new int[n][n];
		for(int i = 0;i<n;i++)
		{
    
    
			for(int j = 0;j<=i;j++)
			{
    
    
				if(j==0 || i == j)
					a[i][j]=1;
			}
		}
		for(int i = 1;i<n;i++)
		{
    
    
			for(int j = 1;j<i;j++)
			{
    
    
				a[i][j] = a[i-1][j] + a[i-1][j-1];
			}
		}		
		
		for(int i = 0;i<n;i++)
		{
    
    
			for(int j = 0;j<=i;j++)
			{
    
    
				System.out.print(a[i][j]+" ");
			}
			System.out.println();
		}
		
	}
 
}

Guess you like

Origin blog.csdn.net/TroyeSivanlp/article/details/108685965