题目描述
Given numRows, generate the first numRows of Pascal’s triangle.
For example, given numRows = 5,
Return
从第三行开始,每行除了最左边和最右边两个数为1,其他数字都是上一行中相邻两个数字之和。根据上述规则可以写出下面的代码:
class Solution {
public:
vector<vector<int> > generateRow1() {
vector<int> row;
row.push_back(1);
vector<vector<int>> r;
r.push_back(row);
return r;
}
vector<vector<int> > generateRow2() {
vector<vector<int>> r = generateRow1();
vector<int> row;
row.push_back(1);
row.push_back(1);
r.push_back(row);
return r;
}
vector<vector<int> > generate(int numRows) {
if (numRows < 1)
{
vector<vector<int> > r;
return r;
}
if (numRows == 1)
return generateRow1();
if (numRows == 2)
return generateRow2();
vector<vector<int> > r = generateRow2();
for (int i = 2; i != numRows; ++i)
{
vector<int> row;
row.push_back(1);
for(int j = 1; j != i; ++j)
{
int next = r[i-1][j-1] + r[i-1][j];
row.push_back(next);
}
row.push_back(1);
r.push_back(row);
}
return r;
}
};
LeetCode (13) Pascal's Triangle (杨辉三角 )
时间: 2024-10-23 05:55:02