题目:
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:
数组基本操作。
【Pascal's Triangle】cpp
时间: 2024-11-03 22:11:24