-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain22.java
More file actions
29 lines (26 loc) · 779 Bytes
/
Main22.java
File metadata and controls
29 lines (26 loc) · 779 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
package HOT100;
import java.util.ArrayList;
import java.util.List;
public class Main22 {
List<String> ans = new ArrayList<String>();
public List<String> generateParenthesis(int n) {
backtrace(new StringBuilder(), 0, 0, n);
return ans;
}
private void backtrace(StringBuilder sb, int open, int close, int max) {
if(sb.length() == max * 2) {
ans.add(String.valueOf(sb));
return;
}
if(open < max) {
sb.append('(');
backtrace(sb, open + 1, close, max);
sb.deleteCharAt(sb.length() - 1);
}
if(close < open) {
sb.append(')');
backtrace(sb, open, close + 1, max);
sb.deleteCharAt(sb.length() - 1);
}
}
}