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 0ce869f

Browse files
Generate Parentheses
1 parent cc4f066 commit 0ce869f

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

‎Backtracking/22-Generate-Parentheses.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''Leetcode- https://leetcode.com/problems/generate-parentheses/'''
2+
'''
3+
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
4+
5+
6+
Example 1:
7+
8+
Input: n = 3
9+
Output: ["((()))","(()())","(())()","()(())","()()()"]
10+
'''
11+
12+
13+
def generateParenthesis(n):
14+
stack = []
15+
res = []
16+
17+
def backtrack(open, close):
18+
if open == close == n:
19+
res.append("".join(stack))
20+
return
21+
22+
if open < n:
23+
stack.append("(")
24+
backtrack(open+1, close)
25+
stack.pop()
26+
27+
if close < open:
28+
stack.append(")")
29+
backtrack(open, close+1)
30+
stack.pop()
31+
32+
backtrack(0, 0)
33+
return res

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,6 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
1616
- [x] [Combination Sum](Backtracking/39-Combination-Sum.py)
1717
- [x] [Combination Sum II](Backtracking/40-Combination-Sum-II.py)
1818
- [x] [Combination Sum III](Backtracking/216-Combination-Sum-III.py)
19+
- [x] [Generate Parentheses](Backtracking/22-Generate-Parentheses.py)
1920

2021

0 commit comments

Comments
(0)

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