打印杨辉三角

分析:

首先要用到队列queue,先进后出

最先q.push(1)属于预存1,杨辉三角上一层比下一层的数字少1

第0层 输出1   队列最终状态  01

第二层 输出 1 1 队列最终状态 011

第三层 输出 1 2 1 队列最终状态 0121

......

//打印杨辉三角 
#include<iostream>
#include<queue> 
using namespace std;
void gcd(int n){
    queue<int> q;
    q.push(1);
    int i,j,s,tmp,t;
    for(i=0;i<n;i++){
        q.push(0);
        s=0;
        for(j=0;j<i+2;j++){
            t=q.front();
            q.pop();
            tmp=t+s;
            q.push(tmp);
            s=t;
            if(j!=i+1) cout<<s<<" ";
        }
        cout<<endl;
    }
    
}
int main()
{
    int n;
    cin>>n;
    gcd(n);
} 
View Code
10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

  

原文地址:https://www.cnblogs.com/helloworld2019/p/10486500.html