-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path022_GenerateParentheses22.java
99 lines (85 loc) · 2.58 KB
/
022_GenerateParentheses22.java
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList();
traverse(0,0,n,"",list);
return list;
}
void traverse(int op, int cp, int n, String prefix, List<String> list){
if((op+cp)/2 == n){
list.add(prefix);
return;
}
if(op<n) traverse(op+1, cp, n, prefix+"(",list);
if(cp<n && cp<op) traverse(op,cp+1,n, prefix+")",list);
}
}
****************************************************************************************
class Solution {
List<String> ans = new ArrayList<String>();
public List<String> generateParenthesis(int n) {
generate(n, 0, new StringBuilder());
return ans;
}
public void generate(int n, int openBrackets, StringBuilder sb){
if(openBrackets == 0 && n == 0){
String temp = sb.toString();
ans.add(temp);
return;
}
if(openBrackets != 0){
sb.append(')');
generate(n, openBrackets-1, sb);
sb.setLength(sb.length() - 1);
}
if(n != 0){
sb.append('(');
generate(n-1, openBrackets+1, sb);
sb.setLength(sb.length() - 1);
}
}
}
*************************************************************************************
class Solution {
public List<String> generateParenthesis(int n) {
int open = n ;
int close = n;
String output = "";
ArrayList<String> list = new ArrayList<>();
solve(open,close,output,list);
return list;
}
public void solve(int open,int close,String output,ArrayList<String> list)
{
if(open == 0 && close == 0)
{
list.add(output);
return;
}
if(open != 0)
{
String output1 = output + "(" ;
solve(open-1,close,output1,list);
}
if(close > open)
{
String output2 = output + ")";
solve(open,close-1,output2,list);
}
}
}
********************************************************************************
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
dfs(n, n, "", res);
return res;
}
private void dfs(int l, int r, String cur, List<String> res) {
if(l == 0 && r == 0){
res.add(cur);
return;
}
if(l > 0) dfs(l-1, r, cur+"(", res);
if(r > l) dfs(l, r-1, cur+")", res);
}
}