Skip to content

Commit 3ed8df3

Browse files
committed
Uses a little bit of recursion and a little bit of checking for valid parentheses,combination of two codes basically
1 parent 459e495 commit 3ed8df3

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

‎22. Generate Parentheses.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution(object):
2+
def generateParenthesis(self, n):
3+
"""
4+
:type n: int
5+
:rtype: List[str]
6+
"""
7+
8+
arr = []
9+
def recursion(string,left,right):
10+
if(left==n and right==n):
11+
arr.append(string)
12+
if(left<=n and right<=n):
13+
recursion(string+"(",left+1,right)
14+
recursion(string+")",left,right+1)
15+
return
16+
17+
recursion("(",1,0)
18+
19+
def valid(string):
20+
stack = []
21+
for i in string:
22+
if(i=="("):
23+
stack.append(")")
24+
else:
25+
if not stack:
26+
return False
27+
else:
28+
stack.pop()
29+
if not stack:
30+
return True
31+
32+
new_arr = []
33+
for i in arr:
34+
if(valid(i)):
35+
new_arr.append(i)
36+
37+
return new_arr

‎ssd.txt

Whitespace-only changes.

0 commit comments

Comments
 (0)