Pascal's Triangle II
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return
Return
[1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
Could you optimize your algorithm to use only O(k) extra space?
class Solution {
public:
vector<int> getRow(int rowIndex) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> r1,r2;
vector<int>* p1 = &r1;
vector<int>* p2 = &r2;
p2->push_back(1);
for(int ii = 0; ii <= rowIndex; ++ii){
swap(p1,p2);
p2->resize(ii+1);
(*p2)[0] = 1;
(*p2)[ii] = 1;
for(int jj = 1; jj < ii; ++jj){
(*p2)[jj] = (*p1)[jj-1] + (*p1)[jj];
}
}
return (*p2);
}
};
No comments:
Post a Comment