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?
杨辉三角,就用一个临时的vector记录上一次求的结果,新的一行由上一行累加算就行了。
class Solution {
public:
vector<int> getRow(int rowIndex) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<int> result, temp;
result.push_back(1);
if (rowIndex == 0) return result;
for (int i = 1; i < rowIndex + 1; ++i)
{
temp = result;
int len = temp.size();
for(int j = 1; j < len; ++j)
{
result[j] += temp[j - 1];
}
result.push_back(1);
}
return result;
}
};