您的位置:首页 > 其它

Pascal's Triangle -leetcode

2013-10-05 20:50 387 查看



Pascal's Triangle

AC Rate: 867/2595
My Submissions

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