分析:
递归实现,如果左括号还有剩余,则可以放置左括号,如果右括号的剩余数大于左括号,则可以放置右括号。
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);
}
}
};