您的位置:首页 > 其它

[leetcode] Pascal's Triangle II

2014-07-14 13:15 477 查看
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<int> res保存结果,求出每行后都替换上次结果
代码:

class Solution {
public:
vector<int> getRow(int rowIndex) {
rowIndex=rowIndex+1;
vector<int> temp;
temp.push_back(1);
vector<int> res;
if(rowIndex<1) return res;
res=temp;
for(int i=1;i<rowIndex;i++){
temp.clear();
temp.push_back(1);
for(int j=1;j<i;j++){
temp.push_back(res[j-1]+res[j]);
}
temp.push_back(1);
res=temp;
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法