Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.
Note that the row index starts from 0.
Example:
Input: 3
Output: [1,3,3,1]
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
方法解析:题目要求只使用额外的O(k) 空间,使用int容器分别记录上一行的结果,和当前的结果
代码如下:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> row1;
vector<int> row2;
for(int i = 0; i <= rowIndex; i++)
{
row2.resize(i);
row2 = row1;
row1.resize(i + 1);
if(i == 0)
{
row1[0] = 1;
continue;
}
for(int j = 0; j < i + 1; j++)
{
if(j == 0 || j == i)
{
row1[j] = 1;
}
else
{
row1[j] = row2[j-1] + row2[j];
}
}
}
return row1;
}
};