zoukankan      html  css  js  c++  java
  • [LeetCode] 22. 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:

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

    给一个数字n,生成所有长度为2n配对正确的括号组合。

    使用递归Recursion一步步构造字符串,当左括号出现次数<n时,就可以放置新的左括号。当右括号出现次数小于左括号出现次数时,就可以放置新的右括号。

    Java:

    public class Solution {
        public ArrayList<String> generateParenthesis(int n) {
            ArrayList<String> res = new ArrayList<String>();
            if (n <= 0) 
                return res;
            helper(res, "", n, n);
            return res;
        }
        
        public void helper(ArrayList<String> result, String current,  int left, int right) { 
            if (left == 0 && right == 0)
                result.add(current);
            if (left > 0)
                helper(result, current + "(", left - 1, right);
            if (right > left)
                helper(result, current + ")", left, right - 1);
        }
    }
    

    Python:

    class Solution:
        # @param an integer
        # @return a list of string
        def generateParenthesis(self, n):
            result = []
            self.generateParenthesisRecu(result, "", n, n)
            return result
        
        def generateParenthesisRecu(self, result, current, left, right):
            if left == 0 and right == 0:
                result.append(current)
            if left > 0:
                self.generateParenthesisRecu(result, current + "(", left - 1, right)
            if left < right:
                self.generateParenthesisRecu(result, current + ")", left, right - 1)
    

    C++:

    class Solution {
    public:
        vector<string> generateParenthesis(int n) {
            vector<string> res;
            generateParenthesisDFS(n, n, "", res);
            return res;
        }
        void generateParenthesisDFS(int left, int right, string out, vector<string> &res) {
            if (left > right) return;
            if (left == 0 && right == 0) res.push_back(out);
            else {
                if (left > 0) generateParenthesisDFS(left - 1, right, out + '(', res);
                if (right > 0) generateParenthesisDFS(left, right - 1, out + ')', res);
            }
        }
    };
    

      

    类似题目:

    [LeetCode] 20. Valid Parentheses 合法括号

    [LeetCode] 32. Longest Valid Parentheses 最长有效括号

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    LDAP安装配置(windows)
    chrome postman插件手动安装
    mabatis insert into on duplicate key
    ZOJ 3641 <并查集+STL>
    ZOJ 3633 <rmq 重点在于转化>
    POJ 2817 状态DP 字符串找最多的重复
    POJ 2771 简单二分图匹配
    POJ 1149 最大流<建图> PIGS
    POJ 3692 二分图最大独立点集
    POJ 2239 简单的二分图求最大匹配
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8497012.html
Copyright © 2011-2022 走看看