a strangle idea


  • 0
    D

    I do think this idea not as good as exsit one, but it is fun. (^_^)

    class Solution 
    {
    public:
        vector<string> generateParenthesis(int n) 
        {
            vector<string> res;
            if(n<=0)
                return res;
            pa(n,res);
            return res;
        }
        void pa(int n,vector<string> &res)  //recursive function
        {
            if(n==1)    //只有一对括号 only one parenthesis
                res.push_back("()");
            else
            {
                pa(n-1,res);    //生成n-1对括号  recursive 
                int len=res.size();
                for(int i=0;i<len;i++)
                {
                    res[i]="()"+res[i];     //add a pair of parenthesis
                    string temp=res[i];     
                    int j=2;
    
                    //将新增的右括号')'往后挪 move new ‘)’ to right position
                    while(res[i][j]!=')')
                    {
                        swap(temp[j],temp[j-1]);   
                        string s=temp;
                        res.push_back(s);
                        j++;
                    }
                }
            }
        }
    };
    

Log in to reply
 

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