[LeetCode] 068: Pascal\'s Triangle II

来源:互联网 发布:js点击按钮让日期增加 编辑:程序博客网 时间:2024/06/14 21:30
[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的博客
原创粉丝点击