题目:
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] ]题目链接
题意:
给一个行数,代表的是Pascal三角形的层数,要求用vector存储Pasicl三角,并将其返回。
通过观察可以得知,Pasicl三角的第i层有i个元素,且对于非首行,非首列,非末列的元素而言,元素的值等于上一层左右连个节点之和,即
nums[i][j] = nums[i-1][j-1] + nums[i-1][j]。
代码如下:
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int> > ans;
for (int i = 0; i < numRows; i ++) {
vector<int> temp;
if (i == 0) temp.push_back(1);
else {
for (int j = 0; j <= i; j ++) {
if (j == 0) {
temp.push_back(ans[i-1][j]);
}
else if (j == i) {
temp.push_back(ans[i-1][j-1]);
}
else {
temp.push_back(ans[i-1][j-1] + ans[i-1][j]);
}
}
}
ans.push_back(temp);
}
return ans;
}
};