Leetcode 119:Pascal‘s Triangle II
技術標籤:algorithm-design演算法leetcode
119.Pascal's Triangle II
Easy
Given an integerrowIndex
, return therowIndexth
row of the Pascal's triangle.
Noticethat the row index starts from0.
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 onlyO
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;
}