这是我的原本代码:
class Solution {
public:
vector<int> getRow(int rowIndex) {
// 1
// 11
// 121
// 1331
// 1461
//怎么表示第一行
// 最后返回的是一个vector,也就是只返回第n行就可以了
// 我们可以创建一个二维vector,最后把n行给一个vector,返回vector即可
vector<vector<int>> vv;
vector<int> v;
for(int i=0;i<=n;i++)
{
for(int j=0;j<=i;j++)
{
vv[i][j]=1;
}
}
}
for(int i=2;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
vv[i][j]=vv[i-1][j]+vv[i-1][j-1];
}
}
for(int i=0;i<=n;i++)
{
for(int j=0;j<=i;j++)
{
v.push_back(vv[i][j]);
}
}
}
return v;
};
经过纠错之后
There are a few issues in the code provided:
- The nested for loops to initialize the 2D vector
vvare incorrect. You should first initialize the rows ofvvand then initialize the elements within each row. - The second set of nested for loops should start from
j=0instead ofj=1to access all elements in the row. - The
count<<vv[i][j]<<" "<<endl;statement should bev.push_back(vv[i][j]);to add the elements to the vectorv.
Here's the corrected code:
class Solution {
public:
vector<int> getRow(int n) {
vector<vector<int>> vv(n+1, vector<int>(n+1, 1));//
vector<int> v;
for(int i=2; i<=n; i++) {
for(int j=1; j<i; j++) {
vv[i][j] = vv[i-1][j] + vv[i-1][j-1];
}
}
for(int j=0; j<=n; j++) {
v.push_back(vv[n][j]);
}
return v;
}
};
This code initializes a 2D vector vv with all values set to 1, and then calculates the values for the nth row using Pascal's triangle logic. Finally, it adds the elements of the nth row to the vector v and returns it.
ps
vector<vector<int>> vv(n+1, vector<int>(n+1, 1));
The linevector<vector> vv(n+1, vector(n+1, 1));creates a 2D vectorvvwithn+1rows andn+1columns, and initializes all elements to the value1`.Let's break it down:
vector<vector<int>>declares a 2D vector where each element of the outer vector is a vector of integers.vv(n+1, vector<int>(n+1, 1))initializes the 2D vectorvvwithn+1rows, where each row is a vector of integers withn+1elements, and each element is initialized to the value1.So, after this line, you have a 2D vector
vvwithn+1rows andn+1columns, where all elements are set to1.`