Pascal's Triangle & II
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>> result; vector<int> row(numRows, 1); if(numRows == 1) result.push_back(row); else if(numRows > 1) { result = generate(numRows - 1); //使用递归的方式 for(int i = 1; i < numRows - 1; i++) row[i] = result[numRows - 2][i - 1] + result[numRows - 2][i]; result.push_back(row); } return result; } };
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?
- 递归方法
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> result(rowIndex + 1, 1); //这里和上面I不一样的是,rowindex为0时,为第一行 if(rowIndex == 0) return result; else { vector<int> tmp = getRow(rowIndex - 1); for(int i = 1; i < rowIndex; i++) result[i] = tmp[i - 1] + tmp[i]; return result; } } };
- 非递归
class Solution { public: vector<int> getRow(int rowIndex) { vector<int> v; if(rowIndex < 0) return v; for(int i = 0; i <= rowIndex; ++i){ v.push_back(0); } for(int j = 0; j <= rowIndex; ++j){ v[rowIndex] = 1; for(int k = rowIndex-1; k > 0; --k){ v[k] = v[k] + v[k-1]; } v[0] = 1; } return v; } };