加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Leetcode 22. Generate Parentheses

发布时间:2020-12-14 05:11:15 所属栏目:大数据 来源:网络整理
导读:https://leetcode.com/problems/generate-parentheses/ Medium Given? n ?pairs of parentheses,write a function to generate all combinations of well-formed parentheses. For example,given? n ?= 3,a solution set is: [ "((()))","(()())","(())()","

https://leetcode.com/problems/generate-parentheses/

Medium

Given?n?pairs of parentheses,write a function to generate all combinations of well-formed parentheses.

For example,given?n?= 3,a solution set is:

[
  "((()))","(()())","(())()","()(())","()()()"
]

?

  • 回溯,DFS。学习判断括号有效的剪枝技巧。
  • https://leetcode.com/problems/generate-parentheses/solution/

 1 class Solution:
 2     def generateParenthesis(self,n: int) -> List[str]:
 3         if n == 0:
 4             return None
 5         
 6         result = []
 7         
 8         def helper(s = ‘‘,left = 0,right = 0):
 9             if len(s) == 2 * n:
10                 result.append(s)
11                 return
12             
13             if left < n:
14                 helper(s + (,left + 1,right)
15             
16             if right < left:
17                 helper(s + ),left,right + 1)
18         
19         helper()
20         return result        
View Python Code

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读