Given numrows, generate the first numrows of Pascal ' s triangle.
For example, given numrows = 5,
Return
[ 1], [ 1,2,1], [ 1,3,3,1], [ 1,4,6,4,1]
Analysis: This problem is actually showing the characteristics of Pascal Triangle: it is a triangular matrix, its top is 1, as (row0). Line 1th (row1) (1&1) Two 1, these 1 are the sum of two numbers above them (not within the triangle as 0). And so on, the resulting line 2nd ( ROW2): 0+1=1;1+1=2;1+0=1. Line 3rd (ROW3): 0+1=1;1+2=3; 2+1=3;1+0=1. This method can produce the following lines.
Idea: Do it directly, create a new line each time, start with each of the 1 and then update from element 1 to i-1.
The code is as follows:
Class Solution {public: vector<vector<int>> generate (int numrows) { vector<vector<int> > res; for (auto I=0;i<numrows;++i) { res.push_back (vector<int> (i+1,1)); for (auto j=1; j<i; ++j) res[i][j] = Res[i-1][j-1] + res[i-1][j]; } return res; }};
Pascal ' s Triangle (Pascal's triangle)