示例:
输入:n为3
输出:[
"((()))",
"(()())"
"(())()",
"()(())",
"()()()"
]
Python解决方案:
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ if not n: return [] self.out = [] self.gen(n) return self.out def gen(self,n,s="",left_use=0,left_remain=0): if len(s) == 2*n: self.out.append(s) return else: if not left_use: self.gen(n,s+"(",left_use+1,left_remain+1) elif left_use < n and left_remain: self.gen(n,s+"(",left_use+1,left_remain+1) self.gen(n,s+")",left_use,left_remain-1) elif left_use < n and not left_remain: self.gen(n,s+"(",left_use+1,left_remain+1) else: self.gen(n,s+")",left_use,left_remain)