题解 | #括号生成#

括号生成

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
} 
全部评论

相关推荐

野猪不是猪🐗:我assume that你must技术aspect是solid的,temperament也挺good的,however面试不太serious,generally会feel style上不够sharp
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务