Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c538d74

Browse files
Merge pull request #156 from rsphoenix02/generate_parenthesis
Added a solution to Leetcode 22. Generate Parentheses problem (Python3)
2 parents 0670c3d + aa5d0c2 commit c538d74

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

‎Leetcode/generate_parenthesis.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
2+
#Description: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
3+
4+
#Difficulty Level: Medium
5+
6+
7+
class Solution:
8+
def generateParenthesis(self, n: int) -> List[str]:
9+
10+
stack = []
11+
res = []
12+
13+
def backtrack(openP, closeP):
14+
15+
if openP == closeP == n:
16+
res.append("".join(stack))
17+
return
18+
19+
if openP > closeP:
20+
stack.append(")")
21+
backtrack(openP, closeP + 1)
22+
stack.pop()
23+
24+
if openP < n:
25+
stack.append("(")
26+
backtrack(openP + 1, closeP)
27+
stack.pop()
28+
29+
backtrack(0, 0)
30+
return res

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /