您的位置:首页 > 其它

[Leetcode] 118. Pascal's Triangle 解题报告

2017-04-28 09:41 393 查看
题目

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: