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]
]
基本思路:
每行比上行多一个元素。
每行第一列和最后一列,均为1。
其他列为上一行的当前列和前一列之和。
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> ans(numRows);
for (int i=0; i<numRows; i++) {
for (int j=0; j<=i; j++) {
ans[i].push_back(j!=0 && j!=i ? ans[i-1][j] + ans[i-1][j-1] : 1);
}
}
return ans;
}
};原文:http://blog.csdn.net/elton_xiao/article/details/45788627