translation
给定一个索引K,返回帕斯卡三角形的第K行。例如,给定K=3,返回[1,3,3,1]。注释:你可以改进你的算法只用O(k)的额外空间吗?
Original
returnof the Pascal‘s triangle.For3,Return [1,3,3,1touse only O(k) extra space?
Analysis
This question is actually to undertake the previous question, I also just finished writing.
Leetcode 118 Pascal ' s Triangle (Pascal Triangle) (vector)
The previous question is to return the complete Pascal triangle:
classSolution { Public: vector<vector<int>>GenerateintNumRows) { vector<vector<int>>Pascalif(NumRows <1)returnPascal vector<int>Root Root.push_back (1); Pascal.push_back (root);if(NumRows = =1)returnPascal Root.push_back (1); Pascal.push_back (root);if(NumRows = =2)returnPascalif(NumRows >2) { for(inti =2; i < numrows; ++i) { vector<int>Temp Temp.push_back (1); for(intj =1; J < Pascal[i-1].size (); ++J) {Temp.push_back (Pascal[i-1][j-1] + pascal[i-1][J]); } temp.push_back (1); Pascal.push_back (temp); }returnPascal } }};
So I stole a lazy, since it is index K, then return it, but efficiency is ...
classSolution { Public: vector<int>GetRow (intRowIndex) {RowIndex + =1; vector<vector<int>>Pascalif(RowIndex <1)returnpascal[0]; vector<int>Root Root.push_back (1); Pascal.push_back (root);if(RowIndex = =1)returnpascal[0]; Root.push_back (1); Pascal.push_back (root);if(RowIndex = =2)returnpascal[1];if(RowIndex >2) { for(inti =2; i < RowIndex; ++i) { vector<int>Temp Temp.push_back (1); for(intj =1; J < Pascal[i-1].size (); ++J) {Temp.push_back (Pascal[i-1][j-1] + pascal[i-1][J]); } temp.push_back (1); Pascal.push_back (temp); }returnPascal[rowindex-1]; } }};
A more efficient approach should be to have some kind of formula, to see what others are writing about ...
vector<int>GetRow (intRowIndex) { vector<int>R R.resize (RowIndex +1); r[0] = R[rowindex] =1; for(Autoi =1; I < (r.size () +1) /2; ++i) {R[i] = r[rowindex-i] = (unsigned Long) R[i-1] * (unsigned Long) (Rowindex-i +1)/I; }returnR;}
Sure enough, the power of mathematics was revealed again. Let me write this formula in Markdown grammar ...
r i =r i 1 ?(INd ex?I+1)/I
Leetcode 119 Pascal ' s Triangle II (Pascal Triangle II) (vector, mathematical formula) (*)