[佇列] 二項式係數值(楊輝三角)
阿新 • • 發佈:2018-12-10
將二項式(a + b)^ i展開,其係數構成楊輝三角形
- 楊輝三角除第一行外,每一行的值是上一行相鄰的兩個數相加
- 左右的邊上都是 1 ,可以看做0 + 1(在最外層加上一個0)
#include<queue>
#include<iostream>
using namespace std;
void Yang(int n)
{
int count = n;//計數器
int L = 0, R = 0;//左右模擬的0值
int first = 1;//第一行的第一個數
int second = 1;//第一行的第二個數
int value = 0;//計算需要插入佇列的值
queue<int> s;//s佇列
s.push(first); // 1
s.push(second); // 1 1
// 行數>1
while (count > 1)//迴圈插入佇列
{
s.push(R); // 在上一行末尾放一個0,便於操作
s.push(1); // 該行從1開始,把1放入
while (s.front() != 0) //掃描到0,走到最右邊了,該行結束
{ //兩個兩個相加,並加入佇列
value = s.front();
s.pop();
value += s.front();
s.push(value);
}
s.pop(); //把最右邊的識別符號0,刪除
count--;
}
for (int i = 0; i <= n; i++)//迴圈輸出
{
cout << s.front() << " ";
s.pop();
}
}
int main()
{
Yang(5);
return 0;
}