Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
Analysis:
Refer to the link to see how Pascal's triangle works.
So basically compose the the current row members according to the previous row.
//////////////////////////////////////////////
//code 4ms
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
for(int i=0;i<numRows;i++){
vector<int> tmp;
for(int j=0;j<i+1;j++){
tmp.push_back(1);
if(j>0 && j<i){
tmp[j]=res[i-1][j-1]+res[i-1][j];
}
}
res.push_back(tmp);
}
return res;
}
};
Using Backtracking: (3m)
class Solution {
public:
void BT(vector<vector<int>> &res, int n){
if(n==1){
vector<int> tmp={1};
res.push_back(tmp);
//return;
}
else{
BT(res,n-1);
vector<int> tmp={1};
for(int i=1;i<n;i++){
if(i>res[n-2].size()-1){
tmp.push_back(1);
}
else tmp.push_back(res[n-2][i]+res[n-2][i-1]);
}
res.push_back(tmp);
//return;
}
}
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
if (numRows==0)return res;
BT(res, numRows);
return res;
}
};
No comments:
Post a Comment