Leetcode 22. 括号生成

22. 括号生成 - 力扣(LeetCode)

 

 

思路 深度优先遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func generateParenthesis(n int) []string {
    res := make([]string, 0)
    var dfs func(temp string, leftCount int, rightCount int)
 
    dfs = func(temp string, leftCount, rightCount int) {
        if leftCount == 0 && rightCount == 0 { //当左括号和右括号的剩余都为0时,返回结果
            tmp := temp
            res = append(res, tmp)
            return
        }
        if leftCount > rightCount { //当左括号还有剩余,右括号已经用完,此情况不符合题意,剪枝
            return
        }
 
        if leftCount > 0 {
            dfs(temp+"(", leftCount-1, rightCount)
        }
        if rightCount > 0 {
            dfs(temp+")", leftCount, rightCount-1)
        }
    }
    dfs("", n, n)
    return res
}

  

  

  


__EOF__

本文作者SoutherLea
本文链接https://www.cnblogs.com/lizhengnan/p/16251060.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   SoutherLea  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示