-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathGenerateParentheses.java
53 lines (47 loc) · 1.39 KB
/
GenerateParentheses.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
package by.andd3dfx.common;
import java.util.ArrayList;
import java.util.List;
/**
* <pre>
* <a href="https://leetcode.com/problems/generate-parentheses/">Task description</a>
*
* Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
*
* Example 1:
* Input: n = 3
* Output: ["((()))","(()())","(())()","()(())","()()()"]
*
* Example 2:
* Input: n = 1
* Output: ["()"]
*
* Example 3:
* Input: n = 4
* ["(((())))","((()()))","((())())","((()))()","(()(()))","(()()())","(()())()","(())(())","(())()()","()((()))",
* "()(()())","()(())()","()()(())","()()()()"]
*
* Constraints:
* 1 <= n <= 8
* <pre/>
*
* @see <a href="https://youtu.be/UMBenJ4PZKU">Video solution</a>
*/
public class GenerateParentheses {
public static List<String> generate(int n) {
List<String> result = new ArrayList<>();
generate(0, 0, "", n, result);
return result;
}
private static void generate(int opened, int closed, String current, int n, List<String> list) {
if (opened + closed == 2 * n) {
list.add(current);
return;
}
if (opened < n) {
generate(opened + 1, closed, current + "(", n, list);
}
if (opened > closed) {
generate(opened, closed + 1, current + ")", n, list);
}
}
}