力扣118题:
给定一个非负整数 numRows
,生成「杨辉三角」的前 numRows
行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
示例 1:
输入: numRows = 5 输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
示例 2:
输入: numRows = 1
输出: [[1]]
提示:1 <= numRows <= 30
#include<iostream>
#include<vector>
using namespace std;
class Solution
{
public:
void generate(int numRows)
{
vector<vector<int>> vv; //类似于二维数组
vv.resize(numRows);
/*开辟numRows个空间,也就相当于开辟了numRows行。这里注意不要用reserve函数,因为该函数没办法初始化*/
for (int i = 0; i < numRows; i++)
{
vv[i].resize(i + 1, 0); /*下三角矩阵,第一行对应一列,第二行对应两列......并且都初始化为0*/
vv[i][0] = vv[i][vv[i].size() - 1] = 1; /*将每行的第一个与最后一个都赋值为1*/
}
for (int i = 0; i < vv.size(); i++)
{
for (int j = 0; j < vv[i].size(); j++)
{
if (vv[i][j] == 0) /*这里只有三角形内部为0*/
{
vv[i][j] = vv[i - 1][j] + vv[i - 1][j - 1];
}
}
}
for (auto& e : vv) //用范围for打印出杨辉三角形
{
for (int& num : e)
{
cout << num << ' ';
}
cout << endl;
}
}
};
int main()
{
int numRows;
cin >> numRows;
Solution s1; //创建对象
s1.generate(numRows); //调用函数
}
验证一下:
在力扣也验证一下: