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]
The Yang Hui triangle mainly has the following five properties:
- The Yang Hui Triangle is made up of positive integers, the numbers are symmetrical, each line starts to grow larger by 1, then becomes smaller and goes back to 1.
- The number of digits in the first row is one.
- The first digit of the line is the number of combinations.
- The number of the first row and the.
- In addition to the leftmost and rightmost digits of each line, each number is equal to the sum of the two digits above its upper-left and upper-right (that is, the first digit of the line equals the sum of the first and the first digits of the first line). This is because there are combinatorial identities:.
Solution 1: Constructed directly according to the construction method of Yang Hui triangle.
classSolution { Public: Vector<vector<int>> Generate (intnumrows) {Vector< vector<int> >Res; for(inti =0; i < numrows; i++) {vector<int> Row (i +1,1); for(intj =1; J < I; J + +) Row[j]= Res[i-1][j-1] + res[i-1][j]; Res.push_back (row); } returnRes; }};
Solution 2: The elements of each row of the Yang Hui triangle are the combined number C (m,n), where n represents the first few rows, m=0,1,..., N, using the formula C (m,n) =n!/m!/(N-M)!
classSolution { Public: Vector<vector<int>> Generate (intnumrows) {Vector< vector<int> >Res; for(inti =0; i < numrows; i++) {vector<int> Row (i +1,1); for(intj =0; J <= I; J + +) Row[j]= Fact (i)/fact (J)/fact (I-j); Res.push_back (row); } returnRes; }Private: Long LongFactintN) {if(N <=1) return 1; Long Longf =1, Res; for(inti =2; I <= N; i++) {res= f *i; F=Res; } returnRes; }};
Note that this does not pass the full test because the numrows is overflow when the calculation is large. Additional formula C (M,n) =c (m-1,n-1) +c (m,n-1) Considering the calculation of combinatorial numbers can be improved:
classSolution { Public: Vector<vector<int>> Generate (intnumrows) {Vector< vector<int> >Res; for(inti =0; i < numrows; i++) {vector<int> row =GetRow (i); Res.push_back (row); } returnRes; }Private: Vector<int> GetRow (intRowIndex) {Vector<int>Row; if(RowIndex <0) returnRow; Row.assign (RowIndex+1,0); for(inti =0; I <= RowIndex; ++i) {if(i = =0) {row[0] =1; Continue; } for(intj = RowIndex; J >=1; --j) Row[j]= Row[j] + row[j-1]; } returnRow; }};
This method is inefficient because, in order to calculate the data for row row, all the data from line 1th to line row-1 is calculated first.
[Leetcode]15. Pascal ' s triangle Yang Hui triangle