118.杨辉三角
程序员文章站
2022-03-15 20:34:23
...
problems:
Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
solutions:
1.结果正确,但是会超时。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> vec;
int n = numRows-1;
if(numRows == 1)
{
vector<int> tip;
tip.push_back(1);
vec.push_back(tip);
}
else
{
vec = generate(n);
vector<int> tip;
tip.push_back(1);
for(int i=0;i<n-1;i++)
{
int m=vec[n-1][i]+vec[n-1][i+1];
tip.push_back(m);
}
tip.push_back(1);
vec.push_back(tip);
}
return vec;
}
};
int main()
{
Solution so;
int n;
cin>>n;
vector<vector<int>> vec;
vec = so.generate(n);
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++)
{
cout<<vec[i][j];
}
cout<<endl;
}
return 0;
}
2.直接构造法,可以通过。
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> vec;
if(numRows == 0) return vec;
else vec.push_back({1});
for(int i=1;i<numRows;i++)
{
vector<int> tip;
for(int j=0;j<=i;j++)
{
if(j==0) tip.push_back(1);
else
if(j==i) tip.push_back(1);
else
tip.push_back(vec[i-1][j-1]+vec[i-1][j]);
}
vec.push_back(tip);
}
return vec;
}
};