Clean solution in C++ taking O(n^2) with explanation


  • 0
    S
        vector<vector<int>> generate(int numRows) {
            vector<vector<int>> ret;
            for ( int i = 0; i < numRows; i++ ) {
                vector<int> row(i+1, 1);
                for ( int j = 1; j < row.size() - 1; j++ ) {
                    row[j] = ret[i-1][j-1] + ret[i-1][j];
                }
                ret.push_back(row);
            }
            return ret;
        }
    

    Explanation:
    Each number is the sum of numbers above it. Each row's size the index of that row.
    At first, initialize each row's all element as 1 and only change the inside elements.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.