A Naive way of solution


  • 0
    W
    class Solution {
    public:
        vector<string>helper(string s)
        {
            set<string>res;
            res.insert("()"+s);
            res.insert(s+"()");
            for(int i=0;i!=s.size();i++)
            {
                if(s[i]=='(')
                {
                    string tmp1=s.substr(0,i+1);
                    string tmp2=s.substr(i+1);
                    string s=tmp1+"()"+tmp2;
                    res.insert(s);
                }
            }
            vector<string>ans;
            for(set<string>::iterator it=res.begin();it!=res.end();it++)
                ans.push_back(*it);
            return ans;
        }
        vector<string> generateParenthesis(int n) {
            vector<string>res;
            if(n==0)
                return res;
            string init="";
            deque<string>dq;
            dq.push_back(init);
            int level=0;
            while(!dq.empty())
            {
                if(n==level)
                {
                    set<string>s;
                    while(!dq.empty())
                    {
                        string f=dq.front();
                        s.insert(f);
                        dq.pop_front();
                        
                    }
                    
                    for(set<string>::iterator it=s.begin();it!=s.end();it++)
                        res.push_back(*it);
                    return res;
                }
                int size=dq.size();
                for(int i=0;i!=size;i++)
                {
                    string front=dq.front();
                    dq.pop_front();
                    vector<string>li=helper(front);
                    for(int i=0;i!=li.size();i++)
                    {
                        dq.push_back(li[i]);
                    }
                }
                level++;
            }
            return res;
        }
        
    };
    

Log in to reply
 

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