分析:
递归实现,如果左括号还有剩余,则可以放置左括号,如果右括号的剩余数大于左括号,则可以放置右括号。
Python:
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
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)
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 and 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);
}
}
};
本文介绍了一种使用递归算法生成所有合法的n对括号组合的方法。通过递归调用,当左括号还有剩余时放置左括号,当右括号剩余数大于左括号时放置右括号。提供了Python及C++两种语言的实现。
291

被折叠的 条评论
为什么被折叠?



