-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm0022.py
66 lines (50 loc) · 1.38 KB
/
m0022.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
60
61
62
63
64
65
66
"""Generate Parentheses
TAG: string
n represents number of parentheses, design a function to generate all VALID
parentheses combination
demo:
input: n = 3
output: [
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
"""
from __future__ import annotations
from typing import Tuple
from itertools import permutations
class Filter(object):
DC = {
1: '(',
-1: ')',
}
@staticmethod
def valid(seq: Tuple[int, ...]):
def helper(seq_: Tuple[int, ...], acc: int = 0):
while acc >= 0 and len(seq_) > 0:
seq_, acc = seq_[1:], acc + seq_[0]
if acc < 0:
return False
else:
return True
return helper(seq, 0)
class Recursion(object):
@staticmethod
def solution(n: int):
ls = set()
def helper(output, first, last, input):
if first == input and last == input:
ls.add(output)
else:
if first < input:
helper(output + "(", first + 1, last, input)
if last < first:
helper(output + ")", first, last + 1, input)
helper("", 0, 0, n)
return ls
if __name__ == '__main__':
input_1 = 3
exp_1 = {"((()))", "(()())", "(())()", "()(())", "()()()"}
assert Recursion.solution(input_1) == exp_1