考察了一些二维vector的使用方法,我和题解写的差不多,题解里用了一个resize函数调整vector大小。
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>>ans(numRows);//行数确定,列数不确定
ans[0].push_back(1);
vector<int>a;
for (int i = 1; i <numRows; i++) {
for (int j = 0; j <=i; j++) {
if (j == 0 || j == i)a.push_back(1);
else a.push_back(ans[i - 1][j - 1] + ans[i - 1][j]);
}
ans[i] = a;
a.clear();
}
return ans;
}
};
//题解做法
class Solution1 {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> ret(numRows);
for (int i = 0; i < numRows; ++i) {
ret[i].resize(i + 1);//resize函数可以调节vector的大小
ret[i][0] = ret[i][i] = 1;
for (int j = 1; j < i; ++j) {
ret[i][j] = ret[i - 1][j] + ret[i - 1][j - 1];
}
}
return ret;
}
};
int main() {
Solution test;
vector<vector<int>>ans = test.generate(5);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++) {
cout << ans[i][j];
}
cout << endl;
}
}