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?
1st iteration:
This is like level iteration of a tree
class Solution {
public:
vector<int> getRow(int rowIndex) {
// invalid input
if (rowIndex < 0) {
return vector<int>(-1,1);
}
// degenerate case
if (rowIndex == 0) {
return vector<int>(1,1);
}
// put extra 0s at beining and end to facilitate caculation
int zeroRow[] = {0,1,0};
vector<int> row(zeroRow, zeroRow + sizeof(zeroRow)/sizeof(int));
int k = 1;
int size = row.size();
// we use only one vector in the loop
while (k <= rowIndex) {
// add extra 0 at begining for this row
row.push_back(0);
// caculate elements of row based on previous row
for (int i = 0; i < size-1; i++) {
row.push_back(row[i]+row[i+1]);
}
// only keep this row by taking out previous row
row.erase(row.begin(), row.begin()+size);
// add tail zero
row.push_back(0);
// update size and k
size = row.size();
k++;
}
// remove extra 0s
return vector<int>(row.begin()+1, row.end()-1);
}
};
2nd iteration, using DP
// Justify input by left-hand
// define T[i][j] as the left-hand justified triangle
// dp transition function is:
// T[i][j] = T[i-1][j-1]+T[i][j-1] if i>0 && j>0
// = 0 if i == 0;
// = 0 if j == 0 execpt 1 if i == 1 && j = 0
// we only need 1D vector to caculate iteratively, as we only need previous row's info.
// we caculate from right-to-left, to avoid overwrite previous row's info.
class Solution {
public:
vector<int> getRow(int rowIndex) {
assert(rowIndex >=0);
// basic case
vector<int> result;
result.resize(rowIndex+2);
result.assign(result.size(), 0);
result[1] = 1;
for (int i = 0; i< rowIndex; i++) {
// right-to-left to avoid duplicate add due to overwrite previous row's info.
for (int j = rowIndex+1; j>0; j--) {
result[j] += result[j-1];
}
}
// take out zero from head
result.erase(result.begin());
return result;
}
};