Skip to content

Commit ea8c360

Browse files
authored
Generated Parenthesis in Java
1 parent 293d3ce commit ea8c360

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

GenerateParentheses.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public List<String> generateParenthesis(int n) {
3+
List<String> ans = new ArrayList();
4+
backtrack(ans, new StringBuilder(), 0, 0, n);
5+
return ans;
6+
}
7+
8+
public void backtrack(List<String> ans, StringBuilder cur, int open, int close, int max){
9+
if (cur.length() == max * 2) {
10+
ans.add(cur.toString());
11+
return;
12+
}
13+
14+
if (open < max) {
15+
cur.append("(");
16+
backtrack(ans, cur, open+1, close, max);
17+
cur.deleteCharAt(cur.length() - 1);
18+
}
19+
if (close < open) {
20+
cur.append(")");
21+
backtrack(ans, cur, open, close+1, max);
22+
cur.deleteCharAt(cur.length() - 1);
23+
}
24+
}
25+
}

0 commit comments

Comments
 (0)