【LeetCode & 剑指offer刷题】回溯法与暴力枚举法题4:Generate Parentheses

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

C++
 
//问题:产生括号对
//方法一:回溯法(并没有回溯,应该就叫普通递归法)
/*
递归,并用两个变量(open, close)记录当前左括号和右括号的个数
 open < n (n为括号对数量)时添加左括号,close<open时添加右括号
Once we add a '(' we will then discard it and try a ')' which can only close a valid '('. Each of these steps are recursively called
举例:(n=3时的递归树)
                                --> (((,3,0,3--> (((),3,1,3--> ((()),3,2,3--> ((())),3,3,3 return
                    --> ((,2,0,3
                                              --> (()(, 3,1,3--> (()(), 3,2,3--> (()()), 3,3,3 return
"",0,0,3 --> (,1,0,3            --> ((), 2,1,3
                                              --> (()), 2,2,3--> (())(, 3,2,3--> (())(), 3,3,3 return
                   
                                              --> ()((,3,1,3--> ()((),3,2,3--> ()(()),3,3,3 return
                    --> (),1,1,3--> ()(, 2,1,3
                                              --> ()(),2,2,3--> ()()(,3,2,3--> ()()(),3,3,3 return
                               
*/
class Solution
{
public:
    vector<string> generateParenthesis(int n)
    {
        vector<string> ans;
        recursion(ans, "", 0, 0, n);
        return ans;
    }
   
private:
    void recursion(vector<string>& ans, string s, int open, int close, int n)
    {
        if(s.length() == 2*n)
        {
            ans.push_back(s);
            return;
        }
       
        //深度优先搜索,分支为加左括号和右括号,深度方向左括号和右括号保证匹配
        if(open < n) recursion(ans, s+'(', open+1, close, n); //递归树有很多分支,遍历到所有可能的情况 
        if(close < open) recursion(ans, s+')', open, close+1, n); //加右括号,直到左右括号相匹配
    }
};
 
 

 

posted @ 2019-01-06 17:12  wikiwen  阅读(150)  评论(0编辑  收藏  举报