基础练习 杨辉三角形
时间限制:1.0s 内存限制:256.0MB
问题描述
杨辉三角形又称Pascal三角形,它的第i+1行是(a+b)i的展开式的系数。
它的一个重要性质是:三角形中的每个数字等于它两肩上的数字相加。
下面给出了杨辉三角形的前4行:
1
1 1
1 2 1
1 3 3 1
给出n,输出它的前n行。
输入格式
输入包含一个数n。
输出格式
输出杨辉三角形的前n行。每一行从这一行的第一个数开始依次输出,中间使用一个空格分隔。请不要在前面输出多余的空格。
样例输入
4
样例输出
1
1 1
1 2 1
1 3 3 1
1 1
1 2 1
1 3 3 1
数据规模与约定
1 <= n <= 34。
#include <iostream> #include <cstring> #include <cmath> using namespace std; int ans[100][100]; void triangle(int n) { int x,y,z; memset(ans,0,sizeof(ans)); for(x=0;x<=n;x++) { ans[x][0]=1; for(y=0;y<=n;y++) { if(x==y) ans[x][y]=1; } } for(x=2;x<n;x++) { for(y=1;y<n;y++) { if(x>=y) { ans[x][y]=ans[x-1][y-1]+ans[x-1][y]; // cout<<ans[x][y]<<" "; } } } for(x=0;x<n;x++) { for(y=0;y<n;y++) { if(x>=y) { // ans[x][y]=a[x-1][y-1]+a[x-1][y]; cout<<ans[x][y]<<" "; } } cout<<endl; } } int main() { int n; while(cin>>n) { triangle(n); } return 0; }
代码仅供参考、