Pascal ' s TriangleTotal accepted:43845 Total submissions:145271my submissions QuestionSolution
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]
Hide TagsArrayHas you met this question in a real interview? Yes No
Discuss
This problem is a simple math problem, the number of n+1 line is calculated by the number of rows n, that is, the first last is 1, the other number of n rows by the number of the first and the first i+1 the sum of
#include <iostream> #include <vector>using namespace std;vector<vector<int>> generate (int NumRows) {vector<int> temp1;vector<int> temp2;vector<vector<int> >templast;if (numRows==0) Return Templast;if (numrows==1) {temp1.push_back (1); Templast.push_back (TEMP1); return templast;} if (numrows==2) {temp1.push_back (1); Templast.push_back (TEMP1); Temp1.push_back (1); Templast.push_back (TEMP1); return templast;} Temp1.push_back (1); Templast.push_back (TEMP1);//First line Temp2.push_back (1), temp2.push_back (1); Templast.push_back ( TEMP2);//second line for (int i=2;i<numrows;i++) {temp1.clear (); int len=temp2.size (); Temp1.push_back (1); for (int i=0;i< len-1;i++) Temp1.push_back (temp2[i]+temp2[i+1]); Temp1.push_back (1); Templast.push_back (TEMP1); Temp2.clear (); TEMP2=TEMP1;} return templast;} int main () {vector<vector<int> > Vec1;vec1=generate (5); int len_n=vec1.size (); for (int i=0;i<len_n;i++) {int len_m=vec1[i].size (); for (int j=0;j<len_m;j++) cout<<vec1[i][j]<< "; CoUt<<endl;}}
leetcode_118 problem--pascal ' s Triangle (simple math problem)