Skip to content

Commit 1c3b75b

Browse files
committed
Recursion - medium - generate balanced parentheses implementation
1 parent cf2dab7 commit 1c3b75b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from typing import List
2+
3+
4+
class TreeInfo:
5+
def __init__(self):
6+
self.results = []
7+
8+
9+
class Solution:
10+
def generateParenthesis(self, n: int) -> List[str]:
11+
12+
# if n == 3,we can fill 6 positions
13+
# we have two conditions
14+
# 1) if opened parenthesis count is less than N
15+
# if true -> we can add another open parenthesis
16+
# 2) if closed parenthesis less than open parenthesis
17+
# if true -> we can add close parenthesis
18+
# if total open+closed parenthesis == 2*n means we hit the base case
19+
# we found a balanced parenthesis set,add to result
20+
def generate(output, n, open_c, close_c, current, ti):
21+
if current == n * 2:
22+
ti.results.append(output)
23+
return
24+
25+
if open_c < n:
26+
generate(output + "(", n, open_c + 1, close_c, current + 1, ti)
27+
28+
if close_c < open_c:
29+
generate(output + ")", n, open_c, close_c + 1, current + 1, ti)
30+
31+
ti = TreeInfo()
32+
generate("", n, 0, 0, 0, ti)
33+
return ti.results

0 commit comments

Comments
 (0)