LeetCode 22. 括號生成(回溯+剪枝)

題目描述

給出 n 代表生成括號的對數,請你寫出一個函數,使其能夠生成所有可能的並且有效的括號組合。
在這裏插入圖片描述

思路

詳見鏈接

代碼

from typing import List
class Solution():
	def generateParenthesis()->List(str):
		res = []
		cur_str = ''
		def dfs(cur_str,left,right):
			if left == 0 and right == 0:
				res.append(cur_str)
				return
			if left > right:
				return
			if left > 0:
				dfs(cur_str + '(',left - 1,right)
			if right > 0:
				dfs(cur_str + ')',left,right - 1)
		dfs(cur_str, n, n)
		return res 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章