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]
]
class Solution {
public:
vector<vector<int> > generate(int numRows) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (numRows < 1)
return vector<vector <int> >();
vector<vector<int> > ans;
vector<int> v1(1, 1);
vector<int> v2(2, 1);
ans.push_back(v1);
if (numRows == 1)
return ans;
ans.push_back(v2);
if (numRows == 2)
return ans;
for (int i = 2; i < numRows; ++i ) {
vector<int> vi(i + 1, 1);
for (int j = 1; j < i; ++j) {
vi.at(j) = ans.at(i-1).at(j-1) + ans.at(i-1).at(j);
}
ans.push_back(vi);
}
return ans;
}
};
本文介绍了一种使用C++实现的方法来生成指定层数的帕斯卡三角形。通过迭代算法,该方法能够高效地生成三角形的每一层,并且能够清晰展示帕斯卡三角形的结构。
145

被折叠的 条评论
为什么被折叠?



