119. 杨辉三角 II

100 阅读2分钟

119. 杨辉三角 II - 力扣(LeetCode)

这是我的原本代码:

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:

  1. The nested for loops to initialize the 2D vector vv are incorrect. You should first initialize the rows of vv and then initialize the elements within each row.
  2. The second set of nested for loops should start from j=0 instead of j=1 to access all elements in the row.
  3. The count<<vv[i][j]<<" "<<endl; statement should be v.push_back(vv[i][j]); to add the elements to the vector v.

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 line vector<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 vector vv with n+1 rows, where each row is a vector of integers with n+1 elements, and each element is initialized to the value 1.

So, after this line, you have a 2D vector vv with n+1 rows and n+1 columns, where all elements are set to 1.`