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?
分析:同I,减小了存储空间。在计算ret[i] = ret[i] + ret[i - 1]时,注意用cur、last来记录值,因为更新后会覆盖需要的值。
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> ret(1, 1);
for(int i = 1; i <= rowIndex; i++) {
int last = 1, cur = 1;
for(int j = 1; j < i; j++) {
cur = ret[j];
ret[j] = cur + last;
last = cur;
}
ret.push_back(1);
}
return ret;
}
};