题解 | #括号生成#

括号生成

http://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca


/**
  * 
  * @param n int整型 
  * @return string字符串一维数组
*/
//DFS
func generateParenthesis( n int ) []string {
    res := []string{}
    var dfs func(int,int,string)
    dfs = func (l, r int, path string) {
        //当括号的数量达到2*n的时候就结束递归
        if 2*n == len(path) {
            res = append(res, path)
            return
        }
        //递归加入左括号
        if l > 0 {
            dfs(l-1, r, path+"(")
        }
        //当右括号的数量多于左括号时,才加入
        //可以达到剪枝效果
        if r > l {
            dfs(l, r-1, path+")")
        }
    }
    dfs(n, n, "")
    return res
} 
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 14:00
不想多说了,什么逆天HR,还要教我礼貌😂
机械打工仔:这不纯傻卵吗,他还操心上别人老板了
投递BOSS直聘等公司7个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务