0ms C++ recursive solution


  • 0
    B
    class Solution {
    private:
        vector<string> ans;
        void par(int n,int k1,int k2,int current,string str){
            //k1 & k2 are used for recoding the number of '(' and ')' in the string.
            //current is the current letter location. 
            if(current==(n*2))
            {// the beginning of the string
                str={"("};
                par(n,k1+1,k2,current-1,str);
            }
            else if(current ==0 ){
                //the end of the string
                if(k1==k2&&k2==n){
                    ans.push_back(str);
                    return;
                }
                cout<<"error!"<<endl;
                return ;
            }
            else{
                if(k1<n){
                    if(k2<k1){
                        par(n,k1,k2+1,current-1,str+")");
                    }
                    par(n,k1+1,k2,current-1,str+"(");
                }
                else{
                    par(n,k1,k2+1,current-1,str+")");
                }
            }
        }
    public:
        vector<string> generateParenthesis(int n) {
            if(!n) return ans;
            par(n,0,0,2*n,string());
            return ans;
        }
    };

Log in to reply
 

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