# LeetCode 22 — Generate Parentheses（C++ Java Python）

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:

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

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

递归实现，如果左括号还有剩余，则可以放置左括号，如果右括号的剩余数大于左括号，则可以放置右括号。
C++实现：
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
generate(n, n, "", res);
return res;
}

void generate(int left, int right, string str, vector<string>& res)
{
if(left == 0 && right == 0)
{
res.push_back(str);
return;
}
if(left > 0)
{
generate(left - 1, right, str + '(', res);
}
if(right > left)
{
generate(left, right - 1, str + ')', res);
}
}
};
Java实现：
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> res = new ArrayList<String>();
generate(n, n, "", res);
return res;
}

public void generate(int left, int right, String str, ArrayList<String> res) {
if (left == 0 && right == 0) {
return;
}
if (left > 0) {
generate(left - 1, right, str + '(', res);
}
if (right > left) {
generate(left, right - 1, str + ')', res);
}
}
}
Python实现：
class Solution:
# @param an integer
# @return a list of string
def generateParenthesis(self, n):
res = []
self.generate(n, n, "", res)
return res

def generate(self, left, right, str, res):
if left == 0 and right == 0:
res.append(str)
return
if left > 0:
self.generate(left - 1, right, str + '(', res)
if right > left:
self.generate(left, right - 1, str + ')', res)
感谢阅读，欢迎评论！

• 评论

• 上一篇
• 下一篇