https://leetcode.com/problems/pascals-triangle/description/
Solution 1.
void dynGen(vector<vector<int>>& res, int n) {
if(n==1) {
res[0][0] = 1;
return;
}
dynGen(res, n-1);
res[n-1][0] = 1;
res[n-1][n-1] = 1;
for(int i=1; i<n-1; i++)
res[n-1][i] = res[n-2][i-1] + res[n-2][i];
}
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
if(numRows == 0) return res;
for(int i=1; i<=numRows; i++) res.push_back(vector<int> (i, 0));
dynGen(res, numRows);
return res;
}
Solution 2.
vector<vector<int> > generate(int numRows) {
vector<vector<int>> res(numRows);
for (int i = 0; i < numRows; i++) {
res[i].resize(i + 1);
res[i][0] = res[i][i] = 1;
for (int j = 1; j < i; j++)
res[i][j] = res[i - 1][j - 1] + res[i - 1][j];
}
return res;
}
No comments:
Post a Comment