-
Notifications
You must be signed in to change notification settings - Fork 0
/
0022.py
60 lines (46 loc) · 1.71 KB
/
0022.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Source: https://leetcode.com/problems/generate-parentheses
# Title: Generate Parentheses
# Difficulty: Medium
# Author: Mu Yang <http://muyang.pro>
################################################################################################################################
# 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:
#
# [
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
# ]
#
################################################################################################################################
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 0:
yield ''
return
for m in range(n):
for left in self.generateParenthesis(m):
for right in self.generateParenthesis(n-m-1):
yield f'({left}){right}'
################################################################################################################################
from itertools import product
class Solution2:
def generateParenthesis(self, n: int) -> List[str]:
if n == 0:
yield ''
return
if n == 1:
yield '()'
return
for m in range(1, n+1):
yield from self.generateParenthesisBase(n, m)
def generateParenthesisBase(self, n: int, m: int):
for ls in product(*(range(n-m+1) for _ in range(m))):
if sum(ls) != n-m:
continue
template = '({})'*m
for subp in product(*map(self.generateParenthesis, ls)):
yield template.format(*subp)