题目
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
方案一(回溯/递归+set)
class Solution:def generateParenthesis(self, n: int) -> List[str]:if n == 0:return []if n == 1:return ["()"]last = self.generateParenthesis(n - 1)ret = set()for each in last:for i in range(len(each) // 2 + 1):ret.add(each[:i] + "()" + each[i:])return list(ret)
方案二(回溯)
class Solution:def generateParenthesis(self, n: int) -> List[str]:if n == 0:return []result = []self.helper(n,n,'',result)return resultdef helper(self,l,r,item,result):if r < l:returnif l == 0 and r == 0:result.append(item)if l > 0:self.helper(l-1,r,item+"(", result)if r > 0:self.helper(l,r-1,item+")", result)
func generateParenthesis(n int) []string {
var res []string
dfs("", &res, n, n)
return res
}
// l, r 为左括号和右括号剩余的个数
func dfs(ans string, res *[]string, l, r int) {
if l > r { // 不是有效的括号
return
}
if l == 0 && r == 0 {
*res = append(*res, ans)
return
}
if l > 0 {
dfs(ans + "(", res, l-1, r)
}
if r > 0 {
dfs(ans + ")", res, l, r-1)
}
return
}
原文
https://leetcode-cn.com/explore/interview/card/2020-top-interview-questions/287/backtracking/1285/
