【原创】杨辉三角问题(queue)
杨辉三角形的构造方式是将三角形每一行两边的元素置为1,其他元素为这个元素上面两个元素之和
如:
1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
//杨辉三角问题 ,使用队列queue实现
#include <iostream>
#include <queue>
using namespace std;
int main()
{
queue<int> tri;
queue<int> next;
tri.push(1);
tri.push(1);
int n=0; //用来存储tri首部元素
int num=0; //杨辉三角的阶数
cout <<"请输入杨辉三角的阶数:";
cin >>num;
//cout <<"1" <<endl <<"1 1" <<endl; //输出杨辉三角的前两阶
for(int i=0;i<num-2;i++)
{
n=tri.front(); //存储tri首部元素的值
tri.pop(); //弹出tri首部元素
next.push(1);
while(!tri.empty())
{
next.push(n+tri.front()); //将tri前一项元素和当前首部元素的和压入next尾部
n=tri.front(); //存储tri当前首部元素的值
tri.pop(); //弹出tri首部元素
}
next.push(1);
//将next所有元素依次压入tri并依次弹出next所有元素
while(!next.empty())
{
tri.push(next.front());
//cout <<next.front() <<" "; //输出杨辉三角第二阶以后的每一阶
next.pop();
}
//cout <<endl;
}
//输出杨辉三角第N阶
while(!tri.empty())
{
cout <<tri.front() <<" ";
tri.pop();
}
system("pause");
return 0;
}