题目:
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
思路:
Easy级别的题目,逐层添加即可。需要注意第一层的特殊情况,因为从第二层开始,每一层都需要额外添加两个1,但是第一层仅仅需要添加一个1。
代码:
class Solution {
public:
vector<vector<int>> generate(int numRows) {
if (numRows <= 0) {
return {};
}
vector<vector<int>> ret(numRows, vector<int>());
ret[0].push_back(1);
for (int i = 2; i <= numRows; ++i) {
ret[i - 1].push_back(1);
for (int j = 1; j <= i - 2; ++j) {
ret[i - 1].push_back(ret[i - 2][j - 1] + ret[i - 2][j]);
}
ret[i - 1].push_back(1);
}
return ret;
}
};