A simple c++ recursion solution


  • 0
    D
    class Solution {
    public:
    vector<string> generateParenthesis(int n) {
        if(n<1) {
            return rs;
        }
        string tmp="";
        pair(n,n,tmp);
        return rs;
    }
    private:
    void pair(int left,int right,string tmp) {
        if(left==0&&right==0) {
            rs.push_back(tmp);
            tmp.clear();
        } else if(left>=0&&left<=right) {
            if(left>0) {
                pair(left-1,right,tmp+"(");
            }
            if(left!=right) {
                pair(left,right-1,tmp+")");
            }
        }
    }
    private:
     vector<string>rs;
    };

Log in to reply
 

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