数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
题解:
函数 generateParenthesis(n int) []string 接受一个整数 n,代表生成括号的对数,返回一个字符串数组,其中包含所有可能的有效括号组合。
函数使用回溯法来生成有效括号组合。回溯法是一种递归的搜索方法,可以用来解决组合问题。在这个问题中,回溯法用来生成所有可能的括号序列。
函数 backtrack(results *[]string, current string, open int, close int, max int) 是一个递归函数,它用来生成括号序列。参数 results 是一个字符串数组指针,用来存储生成的括号序列。参数 current 是当前正在生成的括号序列。参数 open 是当前已经添加的左括号数量。参数 close 是当前已经添加的右括号数量。参数 max 是要生成的括号对数。
函数的基本思路是,从左到右依次添加左括号和右括号,直到添加了指定数量的括号对。在添加括号的过程中,需要满足以下条件:
- 左括号的数量不能超过
max。 - 右括号的数量不能超过已经添加的左括号的数量。
- 当已经添加的括号对数达到
max时,将生成的括号序列添加到结果数组中。
func generateParenthesis(n int) []string {
var results []string
backtrack(&results, "", 0, 0, n)
return results
}
func backtrack(results *[]string, current string, open int, close int, max int) {
if len(current) == max*2 {
*results = append(*results, current)
return
}
if open < max {
backtrack(results, current+"(", open+1, close, max)
}
if close < open {
backtrack(results, current+")", open, close+1, max)
}
}