输出杨辉三角形c++

题目描述
杨辉三角形也叫贾宪三角形,西方叫帕斯卡三角形,其实就是各阶二项式系数排列起来构成的三角形,如下。每行的数字实际上是(a + b) ^ n展开后的各项系数。如下图为杨辉三角的前5行。

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

历史上发现这个三角形的人很多,这里介绍几个主要的,北宋人贾宪约1050年首先使用“贾宪三角”进行高次开方运算。杨辉,字谦光,南宋时期杭州人。在他1261年所著的《详解九章算法》一书中,辑录了如上所示的三角形数表,称之为“开方作法本源”图。欧洲直到1623年以后,法国数学家帕斯卡在13岁时发现了“帕斯卡三角”。
现在,请你编程输出杨辉三角形的前N行。

输入格式
输入只有一行,为一个不大于20的正整数N。

输出格式
输出杨辉三角形的前N行。每一行相邻两个整数之间只有一个空格,最后一个数之后没有多余的空格。

样例
样例输入1
5
样例输出1
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

#include <bits/stdc++.h>
using namespace std;
int num[
C++中,使用队列输出杨辉三角形可以通过以下几种方式实现: ### 方法一:使用自定义的链式队列 ```cpp // 这里假设已经有LinkQueue类的定义 // 以下是使用自定义链式队列的代码示例 #include <iostream> // 假设LinkQueue类定义在某个头文件中,这里省略具体定义 // #include "LinkQueue.h" void YangHuiTriangle(LinkQueue<int>& Q, int n) { // 具体实现省略,需要根据LinkQueue类的接口来编写 } int main() { int n; std::cin >> n; LinkQueue<int> Q; YangHuiTriangle(Q, n); return 0; } ``` 此方法通过自定义的链式队列`LinkQueue`来实现,需要先定义`LinkQueue`类,在`YangHuiTriangle`函数中编写具体的生成杨辉三角形的逻辑,在`main`函数中获取用户输入数`n`,并调用`YangHuiTriangle`函数生成并输出杨辉三角形 [^1]。 ### 方法二:使用标准库的队列 ```cpp #include <iostream> #include <queue> using namespace std; int main() { queue<int> yh; int n; cout << "how many lines do you want to see?" << endl; cin >> n; int i = 1; yh.push(0); yh.push(1); yh.push(0); while (i <= n) { int j = 1; while (j < i + 2) { int k1 = yh.front(); yh.pop(); if (k1 != 0) cout << k1 << " "; int k2 = yh.front(); yh.push(k1 + k2); j++; } yh.push(0); cout << endl; i++; } system("pause"); return 0; } ``` 该方法使用了C++标准库中的`queue`,首先提示用户输入输出杨辉三角形数`n`,然后初始化队列并按照杨辉三角形的规则进元素的入队和出队操作,同时输出每一的元素,直到输出完指定数的杨辉三角形 [^2]。 ### 方法三:另一种使用标准库队列的实现 ```cpp #include <stdlib.h> #include <stdio.h> #include <time.h> #include <iostream> #include <string> #include <vector> #include <queue> using namespace std; int main() { int n; cout << "Input the number:" << endl; cin >> n; int i = 1; queue<int> pre; while (i <= n) { queue<int> out; if (n == 1) { cout << 1 << endl; break; } if (i == 1) { cout << 1 << endl; i++; continue; } else if (i == 2) { cout << 1 << " " << 1 << endl; pre.push(1); pre.push(1); i++; continue; } else if (i >= 3) { out.push(1); for (int j = 0; j < i - 2; j++) { int curr = pre.front(); pre.pop(); out.push(curr + pre.front()); } out.push(1); pre.pop(); } for (int size = 1; size <= i; size++) { int current = out.front(); cout << current << " "; pre.push(current); out.pop(); } cout << endl; i++; } system("pause"); return 0; } ``` 此方法同样使用了C++标准库的`queue`,先获取用户输入数`n`,然后根据不同的数情况进处理,对于第一和第二直接输出,从第三开始,通过队列的入队和出队操作生成每一的元素并输出,直到输出完指定数的杨辉三角形 [^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值