Compute Rows In Pascal's Triangle

Leetcode #118

Description:

Given numRows, generate the first numRows of Pascal's triangle.

Example:

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Idea:

Code:

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> result;
        if(numRows == 0)
            return result;

        result.push_back(vector<int>(1,1));
        for(int i=1; i<numRows; ++i){
            vector<int> nextRow(i+1, 1);
            for(int j=1; j<i; ++j){
                nextRow[j] = result[i-1][j-1] + result[i-1][j];
            }
            // push back should be outside of the assignment loop
            result.push_back(nextRow);
        }
        return result;
    }
};

The next Solution break down the functions

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> result;
        if (numRows == 0) return result;

        vector<int> row(1, 1);
        result.push_back(row);

        for(int i=1; i<numRows; i++){
            vector<int> nextRow = getNextRow(row);
            result.push_back(nextRow);
            row=nextRow;
        }

        return result;
    }

    vector<int> getNextRow(vector<int> preRow){
        int inputSize=preRow.size();
        int outputSize=inputSize+1;
        vector<int> outputRow(outputSize, 1);

        for(int i=1; i<inputSize; i++){
            outputRow[i] = preRow[i-1]+preRow[i];
        }
        return outputRow;
    }
};

results matching ""

    No results matching ""