022-括号生成

Description

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

Example
给出 n = 3,生成结果为:
[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
Solution
//
func generateParenthesis1(n int) []string {
    var result  []string
    addparents(&result,n,n,"")
    return result
}

func addparents(result *[]string,left,right int,str string)  {
    if left == 0 && right == 0 {
        *result = append(*result,str)
    }
    if left  > 0{
         addparents(result,left-1,right,str+ "(")
    }
    if right > 0 && left < right {
        addparents(result,left,right-1,str+ ")")
    }
}




//暴力遍历
func generateParenthesis(n int) []string {
    var result []string
    para := "()"
    for i := 0 ;i < n ;i ++ {
        result = generationPar(result,para)
    }
    maps := map[string]bool{}
    list := make([]string,0)
    for _,item := range result {
        if !maps[item] {
            list = append(list, item)
            maps[item] = true
        }
    }
    return list
}

func generationPar(seeds []string ,para string)[]string  {
    if len(seeds) == 0 {
        return []string{para}
    }
    var result []string
    for _,item := range seeds {
        for i := 0 ;i < len(item) ; i ++ {
            left := item[0:i]
            right := item[i:]
            result = append(result, left+para+right)
        }
    }
    return result
}

leetCode地址