• 【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); //加右括号,直到左右括号相匹配
        }
    };
     
     
  • 相关阅读:
    我不是不懂
    Spring环境搭建,IoC容器初体验~
    备战招聘——信息获取与简历制作
    2013应届毕业生“华为”校招应聘总结
    Java知识积累——Sax解析xml文档
    Java知识积累——同时输出到控制台和指定文件,或直接输出到指定文件
    Java知识积累——静态代码块,非静态代码块,构造器的执行顺序和次数
    修改数据库表结构
    IE6/IE7/IE8/Firefox/Chrome/Safari的CSS hack兼容一览表
    项目代码风格要求
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10229461.html
Copyright © 2020-2023  润新知