C/C++ Programming Learning-Week 10 ⑤ Yang Hui Triangle

Topic link

Title description

Do you remember the Yang Hui triangle that you learned in middle school? The specific definition is not described here, you can refer to the following figure:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Input
input data contains multiple test instances, and the input of each test instance only contains a positive integer n (1<=n<=30), which represents the number of layers of the Yang Hui triangle to be output.

Output
corresponds to each input. Please output the Yanghui triangle of the corresponding level. The integers of each level are separated by a space, and each Yanghui triangle is followed by a blank line.

Sample Input

2 3

Sample Output

1
1 1

1
1 1
1 2 1

Ideas

Except for the first and last elements in the lower layer of Yanghui triangle, the other elements are calculated from the upper layer, and the first and last elements are fixed to 1. Since the question will output the value of Yanghui triangle multiple times, in order to save time, we can initialize it. First store the Yanghui triangle in the array, and then take the number from the array when it needs to be input.

C++ code:

#include<bits/stdc++.h>
using namespace std;
long long yang_hui[35][35];
void Init()
{
    
    
	int n = 32;
	yang_hui[1][1] = 1;
	for(int i = 2; i <= 30; i++)
		yang_hui[i][1] = 1;
	for(int i = 2; i <= n; i++)
		for(int j = 2; j <= i; j++)
			yang_hui[i][j] = yang_hui[i - 1][j - 1] + yang_hui[i - 1][j];
}
int main()
{
    
    
	int n;
	memset(yang_hui, 0, sizeof(yang_hui));
	Init();
	while(cin >> n)
	{
    
    
		for(int i = 1; i <= n; i++)
		{
    
    
			for(int j = 1; j <= i; j++)
				j == 1 ? cout << yang_hui[i][j] : cout << " " << yang_hui[i][j];
			cout << endl;
		}
		cout << endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/113098418