【題目描述】
例5.11 ?打印楊輝三角形的前n(2≤n≤20)行。楊輝三角形如下圖:
當n=5時
? ? ? ? 1
? ? ? 1 ? 1
? ? 1 ? 2 ? 1
? 1 ? 3 ? 3 ? 1
1 ? 4 ? 6 ? 4 ? 1輸出:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1【輸入】
輸入行數n。
【輸出】
輸出如題述三角形。n行,每行各數之間用一個空格隔開。
【輸入樣例】
5
【輸出樣例】
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
【題解代碼】
#include<bits/stdc++.h>
using namespace std;const int N = 1e3 + 10;
int nums[N][N];int main()
{int n; cin >> n;for (int i = 1; i <= n; i++){for (int j = 1; j <= i; j++){if (j == 1 || j == i) nums[i][j] = 1;else nums[i][j] = nums[i - 1][j] + nums[i - 1][j - 1];cout << nums[i][j] << ' ';}cout << endl;}return 0;
}