问题描述:
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?
思路:
这道题和版本一 Pascal’s Triangle 的题目几乎一样,所以改一下返回值就行了,这就有了 code I。
但题目有进阶 O(k) 的要求,于是可以想着只保留上一个数组即可,便是 code II。
代码:
// code I
class Solution {
public:
vector<int> getRow(int rowIndex) {
int numRows = rowIndex+1; // compare to the Pascal's Triangle I,only the index and return value are different
vector<vector<int>> result;
vector<int> temp;
if (numRows == 0) return temp;
temp.push_back(1);
result.push_back(temp);
if (numRows == 1) return temp;
temp.push_back(1);
result.push_back(temp);
if (numRows == 2) return result.back();
for (int i = 3; i <= numRows; i++)
{
vector<int> layer;
layer.push_back(1);
vector<int> former = result[i - 2]; //found the corresponding array
for (int j = 0; j < former.size() - 1; j++)
{
layer.push_back(former[j] + former[j + 1]);
}
layer.push_back(1);
result.push_back(layer);
}
return result.back();
}
};
//code II
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> result;
int numRows = rowIndex+1;
if (numRows == 0) return result;
result.push_back(1);
if (numRows == 1) return result;
result.push_back(1);
if (numRows == 2) return result;
for (int i = 3; i <= numRows; i++)
{
vector<int> pre_result;
pre_result.swap(result); //swap to the easy-operated position
result.push_back(1);
for (int j = 0; j < i - 2; j++)
{
result.push_back(pre_result[j]+pre_result[j+1]);
}
}
result.push_back(1);
return result;
}
};