Recursive way in C++ as a reference


  • 0
    T

    class Solution {
    public:
    vector<vector<int>> generate(int numRows) {

        vector<vector<int>> generate;
       
        if (numRows > 0){
           generateHelper(generate, numRows);
        }
        
        return generate;
    }
    
    void generateHelper(vector<vector<int>>& generate, int numRows){
        
        if (numRows == 1){
            vector<int> temp(1,1);
            generate.push_back(temp);
            return;
        }
        if (numRows == 2){
            vector<int> temp(2,1);
            generateHelper(generate, numRows-1);
            generate.push_back(temp);
        }
        else{
            vector<int> temp;
            generateHelper(generate, numRows-1);
            for (int i = 0; i < numRows; ++i){
                (i == 0 || i == numRows-1) ? temp.push_back(1) : temp.push_back(generate[numRows-2][i-1]+generate[numRows-2][i]);
            }
            generate.push_back(temp);
        }
    }
    

    };


Log in to reply
 

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