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