Problem:
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] ]
Analysis:
There two ways to solve the problem, either compute each row element separately or use inductive method.
The latter cost much more less, so we use the latter one.
Code:
1 class Solution { 2 public: 3 vector<vector<int> > generate(int numRows) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 vector<vector<int> > res; 7 vector<int> tmp; 8 9 if (numRows == 0) return res; 10 if (numRows == 1) { 11 tmp.push_back(1); 12 res.push_back(tmp); 13 return res; 14 } 15 16 tmp.push_back(1); 17 res.push_back(tmp); 18 tmp.push_back(1); 19 res.push_back(tmp); 20 21 for (int i=2; i<numRows; i++) { 22 vector<int> next; 23 next.push_back(1); 24 for (int j=1; j<i; j++) { 25 next.push_back(tmp[j-1] + tmp[j]); 26 } 27 next.push_back(1); 28 29 res.push_back(next); 30 tmp = next; 31 } 32 33 return res; 34 } 35 };
Attention: