当前位置: 代码迷 >> 综合 >> [LeetCode] 068: Pascal\'s Triangle II
  详细解决方案

[LeetCode] 068: Pascal\'s Triangle II

热度:34   发布时间:2023-12-09 05:48:58.0
[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的博客