题目:
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?
分析:
杨辉三角。左右相加。没啥说的。
代码:
最初:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> pre;
for(int i=1;i<=rowIndex+1;++i){
vector<int> res;
res.insert(res.begin(),1);
if(i!=1)res.insert(res.end(),1);
for(int j=1;j<i-1;++j){
res.insert(res.end()-1,pre[j-1]+pre[j]);
}
pre=res;
}
return pre;
}
};
最终:
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res(rowIndex+1);
res[0]=1;
for(int i=1;i<=rowIndex;++i)
for(int j=i;j>0;--j)
res[j]+=res[j-1];
return res;
}
};