[LeetCode] 067: Pascal\'s Triangle

来源:互联网 发布:js点击按钮让日期增加 编辑:程序博客网 时间:2024/06/14 23:10
[Problem]

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]]
[Solution]
class Solution {
public:
vector<vector<int> > generate(int numRows) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<int> > res;
if(numRows <= 0)return res;

// generate
for(int i = 1; i <= numRows; ++i){
vector<int> row;

// the first row
if(i == 1){
row.push_back(1);
}
else{
for(int j = 1; j <= i; ++j){
// the first column or the last column
if(j == 1 || j == i){
row.push_back(1);
}
else{
row.push_back(res[i-2][j-2] + res[i-2][j-1]);
}
}
}
res.push_back(row);
}
return res;
}
};
说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击