-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathGen_Parentheses.java
More file actions
30 lines (26 loc) · 890 Bytes
/
Gen_Parentheses.java
File metadata and controls
30 lines (26 loc) · 890 Bytes
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
import java.util.ArrayList;
import java.util.List;
class Solution {
private void backtrack(int openN, int closedN, int n, List<String> res, StringBuilder stack) {
if(openN == closedN && openN == n){
res.add(stack.toString());
return;
}
if(openN < closedN){
stack.append('(');
backtrack(openN + 1, closedN, n, res, stack);
stack.deleteCharAt(stack.length() - 1);
}
if(closedN < openN){
stack.append(')');
backtrack(openN, closedN + 1, n, res, stack);
stack.deleteCharAt(stack.length() - 1);
}
public List<String> generateParenthesis(int n){
List<String> res = new ArrayList<>();
StringBuilder stack = new StringBuilder();
backtrack(0, 0, n, res, stack);
return res;
}
}
}