标签:
你还在申请一个大的数组来存放杨辉三角吗,你out啦;知道队列么,杨辉三角其实是可以用队列来实现的,一个也好,两个也罢,当然你也可以用N个,那就得看你是怎么想的了。
一、使用一个队列打印杨辉三角
#include<iostream>
#include<queue>
using namespace std;
void print(int n)
{
queue<int> yang;
int i = 1, j, s = 0;
int k =0, t, u;
yang.push(i),yang.push(i);
cout<<yang.front();
for( i = 1; i < n; i++)
{
cout<<endl;
yang.push(k);
for(j = 1; j <= i + 2; j++)
{
t = yang.front();
yang.pop();
u = s + t;
yang.push(u);
s = t;
if(j != i + 2)
cout<<s<<‘ ‘;
}
}
}
int main()
{
for(int i = 1; i < 8; i++)
{cout<<"Case:"<<i<<endl;print(i);cout<<endl;}
return 0;
}
二、使用两个队列打印杨辉三角
#include<iostream>
#include<queue>
using namespace std;
void print(int n)
{
queue<int> yang1;
queue<int> yang2;
int change = 1;
yang1.push(1);
cout<<yang1.front();
for(int i = 1; i < n; i++)
{
cout<<endl;
int temp = 0;
if(change)
{
yang1.push(1);
while(!yang1.empty())
{
cout<<yang1.front()<<‘ ‘;
yang2.push(temp+yang1.front());
temp = yang1.front();
yang1.pop();
}
}
else
{
yang2.push(1);
while(!yang2.empty())
{
cout<<yang2.front()<<‘ ‘;
yang1.push(temp+yang2.front());
temp = yang2.front();
yang2.pop();
}
}
change = !change;
}
}
int main()
{
for(int i = 1; i < 8; i++)
{cout<<"Case:"<<i<<endl;print(i);cout<<endl;}
return 0;
}
三、N个队列?
#include<iostream>
using namespace std;
int main()
{
cout<<"233333333..."<<endl;
return 0;
}
标签:
原文地址:http://www.cnblogs.com/yqbeyond/p/4392004.html