-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathSolution22.java
More file actions
32 lines (28 loc) · 937 Bytes
/
Solution22.java
File metadata and controls
32 lines (28 loc) · 937 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
31
32
package backstracking_problem;
import java.util.ArrayList;
import java.util.List;
/**
* 括号生成:【递归】,分只能添加“(”,只能添加“)”,和有可以添加
* “(”又能添加“)”三种情况。注意“)”的个数时时刻刻不能超过“(”。
*/
public class Solution22 {
public List<String> generateParenthesis(int n) {
add("", 0, 0, n);
return list;
}
List<String> list=new ArrayList<>();
void add(String s, int count1, int count2, int n){
if(count1==count2&&count1<n){
s+="(";
add(new String(s), count1+1, count2, n);
}else if (count1==n){
while (count2<n){
s+=")"; count2++;
}
list.add(new String(s));
}else{
add(new String(s+"("), count1+1, count2, n);
add(new String(s+")"), count1, count2+1, n);
}
}
}