leetcode 22. 括号生成
- 搜索加剪枝,参考了覃超老师的答案
type Result struct {
data []string
}
func generateParenthesis(n int) []string {
r := &Result{}
r._gen("", n, n)
return r.data
}
func (this *Result) _gen(str string, left int, right int) {
// 括号用完了
if left == 0 && right == 0 {
this.data = append(this.data, str)
return
}
// 左括号还有
if left > 0 {
this._gen(str+"(", left-1, right)
}
// 右括号比左括号多
if right > left {
this._gen(str+")", left, right-1)
}
}