Skip to content

Commit ba279a3

Browse files
committed
Iinit
1 parent 6ad6480 commit ba279a3

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Python/Generate_Paranthesis.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#Question: Generate all possible pairs of parenthesis for a given number n
2+
#Solution: Recursive backtracking, keep count of left brackets and right brackets
3+
#Difficulty: Medium
4+
5+
def generateParenthesis(n):
6+
"""
7+
:type n: int
8+
:rtype: List[str]
9+
"""
10+
results = []
11+
def helper(results, string, leftCount, rightCount):
12+
#If we've reached the base case where no more brackets can be added, append the current string to our array
13+
if not leftCount and not rightCount: results += [string]
14+
#If there are still left brackers to be added, add left bracket and recall function with 1 less left bracket but 1 more right bracket (Since we've opened a new bracket that needs to be closed)
15+
if leftCount: helper(results, string + "(", leftCount-1, rightCount+1)
16+
#If there are right brackets that need to be added, add 1 then recall function with 1 less right bracket
17+
if rightCount: helper(results, string + ")", leftCount, rightCount-1)
18+
#Call initially with empty array, empty string, n left brackets and no right brackets
19+
helper(results, "", n, 0)
20+
return results

0 commit comments

Comments
 (0)