Skip to content

Commit ba15601

Browse files
Add GenerateParentheses implementation for generating valid parentheses combinations
1 parent 7f98dfd commit ba15601

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Recursion/GenerateParentheses.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package Recursion;
2+
3+
import java.util.*;
4+
5+
public class GenerateParentheses {
6+
public static List<String> generateParenthesis(int n) {
7+
List<String> list = new ArrayList<>();
8+
backtrack(list, "", 0, 0, n);
9+
return list;
10+
}
11+
12+
private static void backtrack(List<String> list, String ans, int open, int close, int max) {
13+
if (ans.length() == max * 2) {
14+
list.add(ans);
15+
return;
16+
}
17+
if (open < max) {
18+
backtrack(list, ans + "(", open + 1, close, max);
19+
}
20+
if (close < open) {
21+
backtrack(list, ans + ")", open, close + 1, max);
22+
}
23+
}
24+
25+
public static void main(String[] args) {
26+
int n = 3;
27+
List<String> ans = generateParenthesis(n);
28+
System.out.println(ans);
29+
}
30+
}

0 commit comments

Comments
 (0)