Output the first n rows of Yanghui's triangle

topic:

Given an n, please output the first n rows of Yang Hui's triangle

Cough cough, it is a very famous and classic question. I think everyone knows what Yang Hui triangle is, so I won’t repeat the konjac here.

Yang Hui's triangle is a geometric arrangement of binomial coefficients in a triangle, which appeared in the book "Detailed Explanation of Nine Chapters Algorithm" written by Yang Hui, a mathematician in the Southern Song Dynasty in 1261. In Europe, Pascal (1623-1662) discovered this rule in 1654, so this table is also called Pascal's triangle. Pascal's discovery was 393 years later than Yang Hui's and 600 years later than Jia Xian's. Yang Hui's triangle is one of the outstanding research achievements of ancient Chinese mathematics. It visualizes the binomial coefficients in graphics and intuitively reflects some inherent algebraic properties of composite numbers from the graphics. It is a combination of discrete numbers and shapes.

problem solving ideas

It can be seen from the above figure that both sides of Yang Hui's triangle are 1, so the thinking is very clear. Now initialize all the '1's, and push out the rest of the numbers.

Code

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cmath>
using namespace std;

int dp[1010][1010];

void init()
{
    for (int i = 1; i <= 1000; i++)
        dp[i][1] = dp[i][i] = 1;
    for (int i = 2; i <= 1000; i++)
        for (int j = 2; j < i; j++)
            dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j];
}
void out(int n)
{
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= i; j++)
            cout << dp[i][j] << ' ';
        cout << endl;
    }
}
int main()
{
    init();
    int n;
    cin >> n;
    out(n);
    return 0;
}

Guess you like

Origin blog.csdn.net/2301_76331300/article/details/130558587