-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathGenerate Parentheses.java
More file actions
77 lines (64 loc) · 2.05 KB
/
Generate Parentheses.java
File metadata and controls
77 lines (64 loc) · 2.05 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
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
/*
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
*/
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (n == 0) {
return new ArrayList<String>();
}
return helper(n, 0, 0, new StringBuilder());
}
public ArrayList<String> helper(int n, int l, int r, StringBuilder s) {
ArrayList<String> result = new ArrayList<String>();
if (l > n || r > n) {
return result;
}
if (r == n) {
result.add(s.toString());
}
if (l < n) {
StringBuilder ss = new StringBuilder(s);
ss.append("(");
result.addAll(helper(n, l + 1, r, ss));
}
if (r < l) {
StringBuilder ss = new StringBuilder(s);
ss.append(")");
result.addAll(helper(n, l, r + 1, ss));
}
return result;
}
}
/
public class Solution2 {
public ArrayList<String> generateParenthesis(int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ArrayList<String> result = new ArrayList<String>();
if (n == 0) {
return result;
}
helper(n, 0, 0, "", result);
return result;
}
public void helper(int n, int l, int r, String s, ArrayList<String> result) {
if (l == n) {
while (r < n) {
s += ")";
r++;
}
result.add(s);
return;
}
if (l < n) {
helper(n, l + 1, r, s+"(", result);
}
if (r < l) {
helper(n, l, r + 1, s+")", result);
}
}
}