118. Pascal's Triangle

https://leetcode.com/problems/pascals-triangle/

Problem

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Solution

class Solution {
public:
    vector<vector<int>> generate(const int numRows) {
        vector<vector<int>> pascal;
        if (numRows == 0) return pascal;
        pascal.reserve(numRows);
        if (numRows > 0) pascal.push_back({1});
        if (numRows > 1) pascal.push_back({1, 1});
        for (int i = 3; i <= numRows; ++i) {
            vector<int> row; row.reserve(i);
            row.push_back(1);
            const auto &prev_row = pascal.back();
            for (int j = 1; j < prev_row.size(); ++j) row.push_back(prev_row[j - 1] + prev_row[j]);
            row.push_back(1);
            pascal.push_back(row);
        }
        return pascal;
    }
};
  • #math

Last updated

Was this helpful?