Given an index K, return the kth row of the Pascal ' s triangle.
For example, given k = 3,
Return [1,3,3,1]
.
Note:
Could optimize your algorithm to use only O(k) extra space?
Hide TagsArray
Method One: Save all two-bit arrays
classSolution { Public: Vector<int> GetRow (introwidx) {Vector<int>CurLine; Vector<vector<int> >Res; Curline.push_back (1); Res.push_back (CurLine); if(Rowidx = =0) returnCurLine; for(inti =1; I <= rowidx; i++) {curline.clear (); for(intj =0; J < res[i-1].size (); J + +) { if(J = =0) Curline.push_back (1); ElseCurline.push_back (Res[i-1][j-1] + res[i-1][j]); } curline.push_back (1); Res.push_back (CurLine); } returnRes[rowidx]; }};
Method Two: Cur is only related to the previous row, with a rolling array to achieve spatial complexity O (n)
classSolution { Public: Vector<int> GetRow (introwidx) {Vector<int>Preline; Vector<int>CurLine; Curline.push_back (1); if(Rowidx = =0) returnCurLine; for(inti =1; I <= rowidx; i++) {Preline=CurLine; Curline.clear (); for(intj =0; J < Preline.size (); J + +) { if(J = =0) Curline.push_back (1); ElseCurline.push_back (Preline[j-1] +Preline[j]); } curline.push_back (1); } returnCurLine; }};
Pascal ' s Triangle II