题目:
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
C++代码:
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> ret;
for(int i=0; i<numRows; i++){
vector<int> r;
vector<int> prev;
for(int j=0;j<=i;j++){
if(j==0 || j==i){
r.push_back(1);
}else{
prev = ret.back();
int m = prev[j-1]+prev[j];
r.push_back(m);
}
}
ret.push_back(r);
}
return ret;
}
};
结果: