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?
注意:只开辟O(K)的内存空间,所以只保存前一组数列和当前数组,并不断滚动更新即可。
class Solution { public: vector<int> getRow(int rowIndex) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<int> res; vector<int> pre; if(rowIndex == 0) { res.push_back(1); return res; } pre.push_back(1); for(int i = 1; i <= rowIndex; i++) { res.push_back(1); for(int j = 1; j < i+1; j++) { res.push_back( pre[j-1] + (j < pre.size() ? pre[j] : 0) ); } pre.clear(); for(int k = 0; k < res.size(); k++) { pre.push_back(res[k]); } res.clear(); } return pre; } };