Leetcode 22. 括号生成

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

 

 

思路 深度优先遍历

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
}

  

  

  

posted @ 2022-05-09 21:42  SoutherLea  阅读(13)  评论(0编辑  收藏  举报