Skip to content

← leetcode

Pascal's Triangle

· Easy

LeetCode problem 118

Simple simulation question; just build Pascal's Triangle row by row, until you have numRows rows inside.

code

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> ans;
        vector<int> row;
        for (int i = 0; i < numRows; ++i) {
            row.push_back(1);
            if (!ans.empty()) {
                for (int i = 0; i < ans.back().size()-1; ++i) {
                    row[i+1] = ans.back()[i] + ans.back()[i+1];
                }
            }
            ans.push_back(row);
        }
        return ans;
    }
};

complexity

  • Time: O(n)
  • Space: O(1)

time taken

  • 3 minutes and 15 seconds