题解:P5732 【深基5.习7】杨辉三角

· · 题解

梦回学而思四年级奥数。感动。

题目大意

输出杨辉三角的前 n 行。

思路

杨辉三角是一个特殊的数阵。

       1
      1 1
     1 2 1
    1 3 3 1
   1 4 6 4 1
  1 5 10 10 5 1

通俗地讲,杨辉三角中的一个数就等于其上方两个数的和。杨辉三角的两边上的值都为 1。

也就是:

a_{1,1}=1 a_{i,j}=a_{i-1,j-1}+a_{i-1,j}

得到递推方程之后代码就很好写了。记得要初始化。

代码

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<climits>
#define ll long long
#define endl '\n'
using namespace std;
int n;
int a[25][25];
main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    a[0][0]=1;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=i;j++){
            a[i][j]=a[i-1][j-1]+a[i-1][j];
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=i;j++){
            cout<<a[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}