給出 n 代表生成括號的對數,請你寫出一個函數,使其能夠生成所有可能的並且有效的括號組合。
例如,給出 n = 3,生成結果爲:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
思路:遞歸,已經分發的左括號數目必須大於等於右括號的數目。二者又同時小於n
var res []string
func dfs (n int, l int, r int, str string){
if l > n || r > n{
return
}
if l == n && r == n{
res = append(res, str)
}else{
if l<n {
str1 := str + "("
dfs(n, l+1, r, str1)
}
if l>r{
str2 := str+")"
dfs(n, l, r+1, str2)
}
}
}
func generateParenthesis(n int) []string {
res = nil
dfs(n, 0, 0, "")
return res
}