From : https://leetcode.com/problems/pascals-triangle-ii/
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> a(rowIndex + 1);
a[0] = 1;
for(int i = 1; i <= rowIndex; i++) {
for(int j = i; j > 0; j--) {
if (j == i) a[j] = a[j-1];
else a[j] = a[j-1] + a[j];
}
}
return a;
}
};class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res;
if(rowIndex==0) { res.push_back(1); return res;}
int i=1, len=(rowIndex+1)/2;
long long cur=1;
res.push_back(1);
while(i<len) {cur = cur*(rowIndex-i+1)/i; res.push_back(cur);i++; }
if((rowIndex&1)==0) {res.push_back(cur*(len+1)/len);}
for(i=len-1; i>=0; i--) res.push_back(res[i]);
return res;
}
};
本文介绍了一种高效算法来求解帕斯卡三角形的第K行元素。通过两种不同的方法实现:一种使用动态规划直接计算每一行;另一种则利用组合数学原理简化计算过程,特别适用于大数值的情况。
1037

被折叠的 条评论
为什么被折叠?



