[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 List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        StringBuilder path = new StringBuilder();
        if (n > 0) generate(n, path, result, 0, 0);
        return result;
    }
    // l 表示 ‘( ‘出现的次数, r 表示 ‘)‘ 出现的次数
    private static void generate(int n, StringBuilder path,
                                 List<String> result, int l, int r) {
        if (l == n) {
            StringBuilder sb = new StringBuilder(path);
            for (int i = 0; i < n - r; ++i) sb.append(‘)‘);
            result.add(sb.toString());
            return;
        }

        path.append(‘(‘);
        generate(n, path, result, l + 1, r);
        path.deleteCharAt(path.length() - 1);

        if (l > r) {
            path.append(‘)‘);
            generate(n, path, result, l, r + 1);
            path.deleteCharAt(path.length() - 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 最长有效括号

原文地址:https://www.cnblogs.com/lightwindy/p/8497012.html

时间: 2024-12-31 06:58:50

[LeetCode] 22. Generate Parentheses 生成括号的相关文章

leetCode 22.Generate Parentheses (生成括号) 解题思路和方法

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: "((()))", "(()())", "(())()", "()(())", "

[CareerCup] 9.6 Generate Parentheses 生成括号

9.6 Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.EXAMPLEInput: 3Output: ((())), (()()), (())(), ()(()), ()()() LeetCode上的原题,请参见我之前的博客Generate Parentheses 生成括号. 解法一: class Solution

[LeetCode] 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: "((()))", "(()())", "(())()", "()(())", "()()()" 在LeetCo

LeetCode 22. Generate Parentheses (括号生成)

题目标签:Backtracking 建立一个 HashMap 来记录 括号的 数量,利用DFS, 先用 左括号, 在用 右括号, 当 右括号用完的时候 返回.具体看code. Java Solution: Runtime:  1 ms, faster than 85.94 % Memory Usage: 39.5 MB, less than 20.00 % 完成日期:12/12/2019 关键点:HashMap class Solution { HashMap<Character, Intege

22. Generate Parentheses生成指定个括号

生成指定个数的括号,这些括号可以相互包括,但是一对括号的格式不能乱(就是配对的一个括号的左括号要在左边,右括号要在右边) 思维就是从头递归的添加,弄清楚什么时候要添加左括号,什么时候添加右括号 有点像二叉树的建立过程 /* 思路是从第一个符号开始添加,只有两种情况,一种是添加左括号,一种是添加右括号 判断好两种添加的条件后向后添加就行: 1.当左边括号不超过括号数n时可以添加左括号 2.当右括号不超过左括号时可以添加右括号 用递归依次向下添加就行 由于这种数据结构比较像二叉树,代码使用二叉树写的

[LeetCode] 22. Generate Parentheses Java

题目: 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: [ "((()))", "(()())", "(())()", "()(())", "()()()" ]

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: "((()))", "(()())", "(())()", "()(())", "()()()" 解

[LintCode] Generate Parentheses 生成括号

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Have you met this question in a real interview? Example Given n = 3, a solution set is: "((()))", "(()())", "(())()", &qu

leetcode 22 Generate Parentheses

class Solution { public: vector<string> generateParenthesis(int n) { set<string> t; if (n == 0) t.insert(""); else { vector<string> pre = generateParenthesis(n - 1); for (auto a : pre) { for (int i = 0; i < a.size(); ++i) {