My 7-line solution in C++


  • 0
    D

    My idea is similar to other solutions, and I added several optimizations to shorten the code while avoiding overheads of allocating new vectors.

    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> result;
        for (size_t i = 1; i <= numRows; ++i) {
            result.emplace_back(vector<int>(i));
            result.back()[0] = 1; // this can be reduced by using vector<int>(i, 1) on the previous line
            for (size_t j = 1; j < i; ++j)
                result.back()[j] = result[i - 2][j - 1] + (j < i - 1 ? result[i - 2][j] : 0);
        }
        return result;
    }

Log in to reply
 

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