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 题目汇总

  • 相关阅读:
    字典常用操作复习
    列表常用方法复习
    爬虫流程复习
    协程解决素数
    yield 复习
    多线程复习2
    多线程复习1
    异常 巩固3
    logging日志基础示例
    2019最新百度网盘不限速下载教程
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8497012.html
Copyright © 2011-2022 走看看