-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGenerateParentheses.java
More file actions
46 lines (40 loc) · 1.07 KB
/
GenerateParentheses.java
File metadata and controls
46 lines (40 loc) · 1.07 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
package leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* @author eko
* @date 2018/10/21 8:04 PM
*
* 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 GenerateParentheses {
public static void main(String[] args) {
List<String> res = new GenerateParentheses().generateParenthesis(3);
System.out.println(res);
}
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
backtrack(list, "", 0, 0, n);
return list;
}
public void backtrack(List<String> list, String str, int open, int close, int max){
if(str.length() == max*2){
list.add(str);
return;
}
if(open < max)
backtrack(list, str+"(", open+1, close, max);
if(close < open)
backtrack(list, str+")", open, close+1, max);
}
}