杨辉三角
描述
给一整数 n, 返回杨辉三角的前 n 行
0 <= n <= 20
杨辉三角也被叫做帕斯卡三角形. --(Wikipedia)
【样例】
输入 : n = 4
输出 :
[
[1]
[1,1]
[1,2,1]
[1,3,3,1]
]
【方法一】
#include <iostream>
#include <cstdio>
using namespace std;
const int MAXN = 20 + 10;
int num[MAXN][MAXN];
int main() {
int n = 4;
printf("请输入 n 的值:");
while (scanf("%d", &n) != EOF) {
printf("\n");
for (int row = 0; row < n; row++) {
for (int col = 0; col <= row; col++) {
if (col == 0 || col == row) {
num[row][col] = 1;
}else {
num[row][col] = num[row - 1][col - 1] + num[row - 1][col];
}
printf("%3d", num[row][col]);
}
printf("\n");
}
printf("\n");
printf("请输入 n 的值:");
}
return 0;
}
【方法二】
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
int main() {
int n = 5;
cout << "请输入 n 的值:";
while (scanf("%d", &n) |= EOF) {
vector<vector<int>> answer(n, vector<int>());
cout << endl;
for (int row = 0; row < n; row++) {
answer[row].resize(row + 1, 1);
for (int col = 0; col < row; col++) {
answer[row][col] = answer[row - 1][col - 1] + answer[row - 1][col];
}
}
for (int row = 0; row < n; row++) {
for (int col = 0; col <= row; col++) {
cout << answer[row][col] << " ";
}
cout << endl;
}
cout << endl;
cout << "请输入 n 的值:";
}
return 0;
}
【结果】
请输入 n 的值:5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
请输入 n 的值:4
1
1 1
1 2 1
1 3 3 1
请输入 n 的值:3
1
1 1
1 2 1
请输入 n 的值:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)