zoukankan      html  css  js  c++  java
  • [LintCode] Generate Parentheses 生成括号

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

     
    Example

    Given n = 3, a solution set is:

    "((()))", "(()())", "(())()", "()(())", "()()()"

    LeetCode上的原题,请参见我之前的博客Generate Parentheses

    解法一:

    class Solution {
    public:
        /**
         * @param n n pairs
         * @return All combinations of well-formed parentheses
         */
        vector<string> generateParenthesis(int n) {
            if (n == 0) return {};
            vector<string> res;
            helper(n, n, "", res);
            return res;
        }
        void helper(int left, int right, string out, vector<string>& res) {
            if (left < 0 || right < 0 || left > right) return;
            if (left == 0 && right == 0) {
                res.push_back(out);
                return;
            }
            helper(left - 1, right, out + "(", res);
            helper(left, right - 1, out + ")", res);
        }
    };

    解法二:

    class Solution {
    public:
        /**
         * @param n n pairs
         * @return All combinations of well-formed parentheses
         */
        vector<string> generateParenthesis(int n) {
            set<string> res;
            if (n == 0) {
                res.insert("");
            } else {
                vector<string> pre = generateParenthesis(n - 1);
                for (auto a : pre) {
                    for (int i = 0; i < a.size(); ++i) {
                        if (a[i] == '(') {
                            a.insert(a.begin() + i + 1, '(');
                            a.insert(a.begin() + i + 2, ')');
                            res.insert(a);
                            a.erase(a.begin() + i + 1, a.begin() + i + 3);
                        }
                    }
                    res.insert("()" + a);
                }
            }
            return vector<string>(res.begin(), res.end());
        }
    };
  • 相关阅读:
    CentOS 配置epel源
    phpstudy + dvws
    被动信息收集
    Mysql 通过information_schema爆库,爆表,爆字段
    油猴百度云
    浏览器如何弹出下载框
    Ubuntu更新源
    关于cookie
    monitor
    分享一个自制的计算子网划分的小工具
  • 原文地址:https://www.cnblogs.com/grandyang/p/5683142.html
Copyright © 2011-2022 走看看