题目:
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
python代码:
class Solution(object):
def helpler(self, l, r, item, res):
if r < l:
return
if l == 0 and r == 0:
res.append(item)
if l > 0:
self.helpler(l - 1, r, item + '(', res)
if r > 0:
self.helpler(l, r - 1, item + ')', res)
def generateParenthesis(self, n):
if n == 0:
return []
res = []
self.helpler(n, n, '', res)
return res
心得:求解类似问题都是用回溯算法。