118 Pascal ' s Triangle
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]
Main topic:
Enter the number of rows to output as shown in the array. (Yang Hui triangle)
Ideas:
Use a double vector to handle the current line and the next line.
The code is as follows:
Class solution {public: vector<vector<int>> generate (int numrows) { vector<vector<int>> result; if ( numrows == 0) return result; vector<int> curvec; vector<int> nextVec; for (int i = 0;i < numrows; i++) { for (int j = 0;j<=i;j++) { &nbsP; if (j == 0) nextvec.push_back (1); else { if (J >= curvec.size ()) nextvec.push_ Back (Curvec[j-1]); else nextvec.push_back (Curvec[j] + curvec[j-1]); } } result.push_back (Nextvec); Curvec.swap (Nextvec); nextvec.clear (); } return result; }};
2016-08-12 09:34:50
This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1837156
Leetcode 118. Pascal's Triangle array (Yang Hui triangle)