Generate Parentheses

 

    vector<string> generateParenthesis(int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int left_cnt = n,right_cnt = n;
        vector<string> res;
        dfs(left_cnt,right_cnt,"",res);
        return res;
    }
    
    void dfs(int left_cnt,int right_cnt,string str,vector<string>& res)
    {
        if(left_cnt==0&&right_cnt==0)
        {
            res.push_back(str);
            return;
        }
        
        if(left_cnt<right_cnt)
        {
            dfs(left_cnt,right_cnt-1,str+")",res);
            if(left_cnt>0)
                dfs(left_cnt-1,right_cnt,str+"(",res);
        }else
        {
            dfs(left_cnt-1,right_cnt,str+"(",res);
        }
    }

  

posted @ 2013-10-06 14:22  summer_zhou  阅读(119)  评论(0编辑  收藏  举报