楊輝三角形又稱Pascal三角形,它的第i+1行是(a+b)i的展開式的係數。
它的一個重要性質是:三角形中的每個數字等於它兩肩上的數字相加。
下面給出了楊輝三角形的前4行:
1
1 1
1 2 1
1 3 3 1
給出n,輸出它的前n行。
輸入包含一個數n。
1 1
1 2 1
1 3 3 1
1 <= n <= 34。
#include<iostream>
#include<string>
const int maxn = 35;
using namespace std;
int main(void)
{
int a[maxn][maxn] = { 0 };
int n;
cin >> n;
if (n == 1)
{
a[0][0] = { 1 };
cout << a[0][0] << endl;
}
else if (n == 2)
{
a[0][0] = { 1 };
a[1][0] = { 1 };
a[1][1] = { 1 };
cout << a[0][0] << endl << a[1][0] << " " << a[1][1] << endl;
}
else if (n >= 3)
{
a[0][0] = { 1 };
a[1][0] = { 1 };
a[1][1] = { 1 };
cout << a[0][0] << endl << a[1][0] << " " << a[1][1] << endl;
for (int i = 2; i < n; i++)
{
a[i][0] = { 1 };
for (int j = 1; j < n; j++)
{
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
}
}
for (int i = 2; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (a[i][j] == 0)
{
break;
}
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}