119. Pascal's Triangle II
Easy
Given an integer rowIndex, return the rowIndexth row of the Pascal's triangle.
Notice that the row index starts from 0.

In Pascal's triangle, each number is the sum of the two numbers directly above it.
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
Example 1:
Input: rowIndex = 3 Output: [1,3,3,1]
Example 2:
Input: rowIndex = 0 Output: [1]
Example 3:
Input: rowIndex = 1 Output: [1,1]
Constraints:
0 <= rowIndex <= 33
解法1:
纯数学法。杨辉三角形每行就是
比如第3行(从0开始),.
那么,我们怎么从呢?
根据可得
代码如下:
注意coeff中间可能会越界,所以要开long long。
时间复杂度O(n),空间复杂度O(1)。
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res;
long long coeff = 1;
res.push_back(1);
for (int i = 1; i <= rowIndex; i++) {
coeff = coeff * (rowIndex - i + 1) / i;
res.push_back((int)coeff) ;
}
return res;
}
};
解法2:
迭代 。我用了两个循环,而且还有一个辅助vector。时间复杂度O(n^2),空间复杂度O(n),效率不高。
```
#include <iostream>
#include <vector>
using namespace std;
vector<int> getRow(int rowIndex) {
if (rowIndex==0) return vector<int>(1,1);
if (rowIndex==1) return vector<int>(2,1);
vector<int> result(rowIndex+1, 1);
for (int i=2; i<=rowIndex; ++i) {
vector<int> prevResult=result;
for (int j=1; j<i; ++j) {
result[j]+=prevResult[j-1];
}
}
return result;
}
int main()
{
for (int k=0; k<=4; ++k) {
vector<int> a=getRow(k);
for (auto i:a) cout<<i<<" ";
cout<<endl;
}
return 0;
}
本文介绍了解决LeetCode上题目“Pascal's Triangle II”的两种方法:一种是利用数学公式直接计算每一项,时间复杂度为O(n),空间复杂度为O(1);另一种是使用迭代的方法构建整个行的内容,时间复杂度为O(n^2),空间复杂度为O(n)。

295

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



