Wednesday, March 9, 2016

LeetCode Q119: Pascal's Triangle II

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 numRows) {
numRows++;
vector<int> newRow;
vector<int> lastRow;
for(int i=1; i<=numRows; i++){
for(int j=1; j<=i;){
if(j==1||j==i){
newRow.push_back(1);
j++;
}
else
for(int k=0; k<lastRow.size()-1; ++k, ++j)
newRow.push_back(lastRow[k]+lastRow[k+1]);
}
lastRow=newRow;
newRow.clear();
}
return lastRow;
}
};
view raw Q119.cpp hosted with ❤ by GitHub

No comments:

Post a Comment