Skip to content

Commit b51b999

Browse files
authored
Merge pull request #202 from c99SRS/beta
added parenthesis qns
2 parents 70ab304 + 78f843c commit b51b999

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Coding/GenerateParentheses.java

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
Generate Parentheses
3+
4+
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
5+
6+
7+
8+
Example 1:
9+
10+
Input: n = 3
11+
Output: ["((()))","(()())","(())()","()(())","()()()"]
12+
13+
Example 2:
14+
15+
Input: n = 1
16+
Output: ["()"]
17+
18+
19+
20+
Constraints:
21+
1 <= n <= 8
22+
23+
*/
24+
25+
class Solution {
26+
27+
List<String> ansList = new ArrayList();
28+
public List<String> generateParenthesis(int n) {
29+
30+
StringBuilder curr = new StringBuilder();
31+
32+
33+
generate(curr,0,0,n);
34+
35+
return ansList;
36+
}
37+
38+
void generate(StringBuilder curr,int openCount,int closedCount, int n){
39+
40+
41+
if(openCount == n && closedCount == n){
42+
ansList.add(curr.toString());
43+
return;
44+
}
45+
46+
if(openCount > n || closedCount > n)
47+
return;
48+
49+
50+
// choice 1
51+
if(openCount < n){
52+
curr.append("(");
53+
generate(curr, openCount+1, closedCount, n);
54+
curr.deleteCharAt(curr.length()-1);
55+
}
56+
57+
// choice 2
58+
if(openCount > closedCount){
59+
curr.append(")");
60+
generate(curr, openCount, closedCount+1, n);
61+
curr.deleteCharAt(curr.length()-1);
62+
}
63+
64+
return;
65+
}
66+
67+
}

0 commit comments

Comments
 (0)