zoukankan      html  css  js  c++  java
  • 【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); //加右括号,直到左右括号相匹配
        }
    };
     
     
  • 相关阅读:
    ios---图片缩放
    ios---清除缓存
    ReactNative---组件种类
    Linux 用户和用户组管理
    Linux 文件与目录管理
    linux文件的基本属性
    xshell 快速复制打开之前用过的ssh
    ll 和 ls -l的详解
    laravel rbac的用户 角色 权限的crud
    laravel 中的rbac自己简单的实现
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10229461.html
Copyright © 2011-2022 走看看