forked from havanagrawal/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_22.java
69 lines (59 loc) · 1.72 KB
/
_22.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
package com.fishercoder.solutions;
import com.fishercoder.common.utils.CommonUtils;
import java.util.ArrayList;
import java.util.List;
/**
* 22. Generate Parentheses
*
* 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 _22 {
public static class Solution1 {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList();
backtrack(result, "", 0, 0, n);
return result;
}
void backtrack(List<String> result, String str, int left, int right, int max) {
if (str.length() == max * 2) {
result.add(str);
return;
}
if (left < max) {
backtrack(result, str + "(", left + 1, right, max);
}
if (right < left) {
backtrack(result, str + ")", left, right + 1, max);
}
}
}
public static class Solution2 {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList();
if (n == 0) {
return result;
}
helper(result, "", n, n);
return result;
}
void helper(List<String> result, String par, int left, int right) {
if (left > 0) {
helper(result, par + "(", left - 1, right);
}
if (right > left) {
helper(result, par + ")", left, right - 1);
}
if (right == 0) {
result.add(par);
}
}
}
}