您的位置:首页 > 其它

[LeetCode] 068: Pascal\'s Triangle II

2017-09-10 20:50 435 查看
[Problem]
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?

[Analysis]
需要注意将每个元素转换成long long ,否则使用int可能造成溢出。

[Solution]
class Solution {
public:
vector<int> getRow(int rowIndex) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<int> res;
if(rowIndex < 0)return res;

for(int i = 0; i <= rowIndex; ++i){
if(i == 0){
res.push_back(1);
}
else{
long long pre = res.back();
if((rowIndex+1)%2 != 0 || i != (rowIndex+1)/2){
res.push_back(pre * (rowIndex+1-i) / i);
}
else{
res.push_back(pre);
}
}
}
return res;
}
};
说明:版权所有,转载请注明出处。Coder007的博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: