题目:
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三角形,每一行的元素等于前一行相邻两个元素的和。返回第k行元素。
思路:
此题是118题的后续,重点在于需要用O(k)的空间复杂度。只需要使用一个记录前一行的整型vector,新的一行就是上一行相邻两两元素的和。
代码:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> result;
vector<int> temp;
for (int i=0;i<rowIndex+1;i++)
{
temp.clear();
temp=result;
result.resize(i+1,0);
if(i==0)
{
result[0]=1;
continue;
}
for (int j=0;j<=i;j++)
{
if(j-1<0)
{
result[j]=0+temp[j];
}
else if(j>=i)
{
result[j]=temp[j-1]+0;
}
else
{
result[j]=temp[j-1]+temp[j];
}
}
}
return result;
}
};
结果: