119. Pascal's Triangle II
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行(从0开始);空间复杂度为O(k);
从第0行开始生成,每次利用已经生成的行,在原有空间上生成下一行,直到生成所要求的行。
代码入下:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> pascal;
pascal.push_back();
int m = ;
for(int i = ; i <= rowIndex; i++)
{
if(rowIndex == )
{
return pascal;
}
for(int j = ; j < i+; j++)
{
if(j == i)
{
pascal.push_back();
break;
}
int n = pascal[j];
pascal[j] = m + n;
m = n;
}
}
return pascal;
}
};