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) {
vector<int> ret(rowIndex+1, 1);
for(int i=0; i<=rowIndex; i++)
{
int last = 1;
for(int j=0; j<=i; j++)
{
if (j == 0 || j == i)
ret[j] = 1;
else
{
//remember the current value before it is overrided
int tmp = ret[j];
ret[j] += last;
last = tmp;
}
}
}
return ret;
}
};
No comments:
Post a Comment