给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
答案:
func generateParenthesis(n int) []string {
var result []string
recall(&result, "", 0, 0, n)
return result
}
func recall(result *[]string, backString string, leftCount int, rightCount int, max int) {
if len(backString) == 2*max {
*result = append(*result, backString)
}
if leftCount < max {
recall(result, backString+"(", leftCount+1, rightCount, max)
}
if rightCount < leftCount {
recall(result, backString+")", leftCount, rightCount+1, max)
}
}