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]
]
1 class Solution { 2 public: 3 vector<vector<int> > generate(int numRows) { 4 5 vector<vector<int>> result; 6 if(numRows==0) return result; 7 vector<int> tem; 8 tem.push_back(1); 9 result.push_back(tem); 10 if(numRows==1) return result; 11 tem.push_back(1); 12 result.push_back(tem); 13 if(numRows==2) return result; 14 for(int i=2;i<numRows;i++){ 15 vector<int> solu(i+1,1); 16 for(int j=1;j<i;j++){ 17 solu[j] = result[i-1][j-1]+result[i-1][j]; 18 } 19 result.push_back(solu); 20 } 21 return result; 22 } 23 24 };
II:
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 you optimize your algorithm to use only O(k) extra space?
1 class Solution { 2 public: 3 vector<int> getRow(int rowIndex) { 4 vector<int> array; 5 for (int i = 0; i <= rowIndex; i++) { 6 for (int j = i - 1; j > 0; j--) { 7 array[j] = array[j - 1] + array[j]; 8 } 9 array.push_back(1); 10 11 } 12 return array; 13 } 14 };