another c++ solution, easy to understand.


  • 0
    Z
       vector<string> generateParenthesis(int n) {
            vector<string> ret;
            if (n == 1) {
                return {"()"};
            }
            set<string> set_;
            vector<string> subParents = generateParenthesis(n-1);
            for (auto& s : subParents) {
                int len = s.length();
                for (int i = 0; i < len; i++) {
                    string s1 = s.substr(0, i);
                    string s2 = s.substr(i, len-i);
                    set_.insert(s1 + "()" + s2);
                }
                
            }
            copy(set_.begin(), set_.end(), back_inserter(ret));
            
            return ret;
        }
    

Log in to reply
 

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