C++ 0ms recursive and iterative 2 simple solutions


  • 0
    Z
    class Solution {
    public:
    vector<vector<int>> generate(int numRows) {
        //return solution1(numRows);        //recusive
        return solution2(numRows);      //iterative
    }
    private:
    vector<vector<int>> v;
    vector<vector<int>> solution1(int numRows){
        if(!numRows) return v;
        subSol1(-1, numRows);
        return v;
    }
    void subSol1(int cur, int row){
        if(cur + 1 == row) return;
        v.push_back(vector<int>());
        v[cur + 1].push_back(1);
        if(row == 1) return;
        if(cur >= 0){
            for(int i = 1; i <= cur; i++)
                v[cur + 1].push_back(v[cur][i - 1] + v[cur][i]);
            v[cur + 1].push_back(1);
        }
        subSol1(cur + 1, row);
    }
    vector<vector<int>> solution2(int numRows){
        if(!numRows) return v;
        for(int i = 0; i < numRows; i++){
            v.push_back(vector<int>());
            v[i].push_back(1);
            if(i > 0){
                for(int j = 1; j < i; j++)
                    v[i].push_back(v[i - 1][j - 1] + v[i - 1][j]);
                v[i].push_back(1);
            }
        }
        return v;
    }
    };

Log in to reply
 

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