废话不多说,先看输出结果
下面是代码思路:
使用动态二维数组来记录n行杨辉三角的数值,没有数值的部分让其值为0,先给第一行的1赋值,然后除了最后一行的第一个和最后一个元素,都有
a[current_line - 1][j] = a[current_line - 2][j - 1] + a[current_line - 2][j + 1];
current用来记录当前行数,每次赋值列数加2,到2n-1的时候打印换行。
下面是实现的代码:
#include <iostream>
using namespace std;
void yanghuisanjiao(int line);
int main()
{
yanghuisanjiao(20);
}
void yanghuisanjiao(int n)
{
int** a = new int* [n];
for (int i = 0; i < n; i++)
{
a[i] = new int[2 * n - 1];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2 * n - 1; j++) {
a[i][j] = 0;
}
}
a[0][n - 1] = 1;
for ( int current_line = 2; current_line <= n; current_line++) {
int count = 0;
for (int j = n - current_line; count < current_line; j += 2) {
if (current_line - 1 == n - 1 && (j == 0 || j == 2 * n - 2)) {
a[current_line - 1][j] = 1;
}
else {
a[current_line - 1][j] = a[current_line - 2][j - 1] + a[current_line - 2][j + 1];
}
count++;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2 * n - 1; j++) {
if (a[i][j] != 0) {
cout << a[i][j];
}
else {
cout << " ";
}
if (j == 2 * n - 2) {
cout << endl;
}
}
}
for (int i = 0; i < n; i++)
{
delete[] a[i];
}
delete[] a;
}