原题:
Problem Description
还记得中学时候学过的杨辉三角吗?具体的定义这里不再描述,你可以参考以下的图形:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Input
输入数据包含多个测试实例,每个测试实例的输入只包含一个正整数n(1<=n<=30),表示将要输出的杨辉三角的层数。
Output
对应于每一个输入,请输出相应层数的杨辉三角,每一层的整数之间用一个空格隔开,每一个杨辉三角后面加一个空行。
Sample Input
2 3
Sample Output
1
1 1
1
1 1
1 2 1
**KEY:**了解杨辉三角的性质,利用递推进行计算,注意输出格式。(如果没弄明白怎么递推可直接看最后的解题思路)
代码:
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
int Layer_Num = 0;//层数
int Present_Floor[1000];//当前层
int Upper_Floor[1000];//上一层
while (cin >> Layer_Num)
{
for (int i = 1; i <= Layer_Num; i++)
{
memset(Present_Floor,0,sizeof(Present_Floor)); //清零输入当前层
for (int j = 0; j < i; j++)
{
if (j == 0 && j == i - 1) //层数为1
{
Present_Floor[j] = 1;
}
else if ((j == 0 && j != i - 1) || (j == i - 1 && j != 0)) //每层头尾
{
Present_Floor[j] = 1;
}
else if (j != 0 && j != i - 1) //每层中间
{
Present_Floor[j] = Upper_Floor[j - 1] + Upper_Floor[j];
}
}
for (int k = 0; k < i; k++)
{
if (k != i - 1) cout << Present_Floor[k]<<" ";
if (k == i - 1) cout << Present_Floor[k];
}
cout << endl;
memcpy(Upper_Floor, Present_Floor, sizeof(Present_Floor)); //复制当前层内容到上一层
}
cout << endl;
}
return 0;
}
**解题思路:**利用前一层数字递推出下一层数字,每层数字单独输出。前一行除第一个和最后一个数字之外,中间数字两两相加就是下一行中间的数字。