题目:
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
代码:
class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int> > ret; if ( numRows<1 ) return ret; vector<int> pre, curr; for ( int i=0; i<numRows; ++i ) { curr.clear(); curr.push_back(1); for ( int j=0; j<pre.size(); ++j ) { if ( j==pre.size()-1 ){ curr.push_back(1); } else{ curr.push_back(pre[j]+pre[j+1]); } } pre = curr; ret.push_back(curr); } return ret; } };
tips:
数组基本操作。
==============================================
第二次过这道题,代码更简洁了。
class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int> > ret; if ( numRows<1 ) return ret; vector<int> pre; pre.push_back(1); ret.push_back(pre); for ( int i=1; i<numRows; ++i ) { pre = ret.back(); vector<int> curr; curr.push_back(1); for ( int j=1; j<pre.size(); ++j ) curr.push_back(pre[j-1]+pre[j]); curr.push_back(1); ret.push_back(curr); } return ret; } };
===========================================
第三版,更简洁了一些
class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int> > ret; if (numRows==0) return ret; vector<int> tmp; tmp.push_back(1); ret.push_back(tmp); for ( int i=1; i<numRows; ++i ) { for ( int j=tmp.size(); j>0; --j ) tmp[j] = tmp[j] + tmp[j-1]; tmp.push_back(1); ret.push_back(tmp); } return ret; } };