一.队列求解:
#include<bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
int n;
while(~scanf("%d", &n) && n > 0){
queue<int> q;
printf("%d\n", 1);
q.push(0);
q.push(1);
q.push(0);
for(int i = 2; i<= n; i++){
for(int j = 1; j <= i; j++){
int val = q.front();
q.pop();
val += q.front();
q.push(val);
printf("%d ", val);
}
q.push(0);
printf("\n");
}
}
return 0;
}
输入数据:
6
10
输出数据:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
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
二.普通求解:
#include <iostream>
using namespace std;
int main()
{
int num;
cin >> num;
int a[num][num];
int i, j;
for (i = 0; i < num; i++)
{
for (j = 0; j <= i; j++)
{
if (j == 0 || i == j)
a[i][j] = 1;
else
{
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}
输入数据:
5
输出结果:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
三.杨辉三角改进:
#include <iostream>
using namespace std;
int main()
{
int num; //代表着要打印的行数
cin >> num; //输入行数
int a[num][num]; //定义一个二维数组,但是打印的时候只打印一部分,不是打印全部
int i, j; //i代表行,j代表列
for (i = 0; i < num; i++)
{
if (i != num) //在每一行输出之前判断是否是num,若不是num,则根据数学规律,输出空格
{
for (int k = num - i - 1; k > 0; k--)
cout << " ";
}
for (j = 0; j <= i; j++)
{
if (j == 0 || i == j)
a[i][j] = 1;
//如果是第一列或者是每一行中行数与列数相等的那一列
else
{
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
//该行列的数字为上上一行的左下方和右下方的数字之和
}
cout << a[i][j] << " "; //在每一个输出之间加空格
}
cout << endl; //在每一行之后输出一个换行符,
//所以是在第一个for循环外,第二个for循环内输出换行符
}
return 0;
}
输入数据:
5
输出结果:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1