-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateParentheses.java
More file actions
38 lines (31 loc) · 1.09 KB
/
Copy pathGenerateParentheses.java
File metadata and controls
38 lines (31 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package Backtracking.Day_12;
import java.util.ArrayList;
import java.util.List;
public class GenerateParentheses {
public static void main(String[] args) {
List<String> ans = generateParenthesis(3);
System.out.print(ans);
}
public static List<String> generateParenthesis(int n) {
// Resultant list
List<String> result = new ArrayList<>();
/// Recursively generate parentheses
generateParenthesis(result, "", 0, 0, n);
return result;
}
public static void generateParenthesis(List<String> result, String s, int open, int close, int n) {
// Base case
if (open == n && close == n) {
result.add(s);
return;
}
// If the number of open parentheses is less than the given n
if (open < n) {
generateParenthesis(result, s + "(", open + 1, close, n);
}
// If we need more close parentheses to balance
if (close < open) {
generateParenthesis(result, s + ")", open, close + 1, n);
}
}
}