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] ]
class Solution { public: vector> generate(int numRows) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<int> > ret; if (!numRows) return ret; vector<int> firstRow; firstRow.push_back(1); ret.push_back(firstRow); for (int i = 1; i < numRows; ++i) { vector<int> lastRow = ret[i - 1]; vector<int> row; for (int j = 0; j <= i; ++j) { if (j != 0 && j != i) { row.push_back(lastRow[j] + lastRow[j - 1]); } else if (j == 0) { row.push_back(lastRow[j]); } else { row.push_back(lastRow[j - 1]); } } ret.push_back(row); } return ret; } };
No comments:
Post a Comment