22. generate parentheses

问题

https://leetcode.com/problems/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:

1
2
3
4
5
6
7
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

思路

方法一:遍历所有可能的组合情况,对于符合条件的加入到结果中,不满足的忽略;
方法二:利用DFS的思想,递归左括号小于右括号且用完了所有的括号的所有情况,直接加入到结果中;

代码

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
public boolean (String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(')');
} else if (c == '{') {
stack.push('}');
} else if (c == '[') {
stack.push(']');
} else if (stack.isEmpty() || stack.pop() != c) {
return false;
}
}
return stack.isEmpty();
}

public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
if (n <= 0) {
return res;
}
genParenthesis(res, new StringBuilder(), 0, n * 2);
return res;
}

private void genParenthesis(List<String> res, StringBuilder sb, int index, int n) {
if (sb.length() == n) {
if (isValid(sb.toString())) {
res.add(sb.toString());
}
return;
}
sb.append('(');
genParenthesis(res, sb, index + 1, n);
sb.deleteCharAt(sb.length() - 1);
sb.append(')');
genParenthesis(res, sb, index + 1, n);
sb.deleteCharAt(sb.length() - 1);
}


public void dfs(List<String> res, String cur, int l, int r) {
System.out.println("res:" + cur);
if(l == 0 && r == 0) {
res.add(cur);
return;
}
if(l > 0) {
dfs(res, cur + "(", l - 1, r);
}
if(l < r) {
dfs(res, cur + ")", l, r -1);
}

}

public List<String> generateParenthesis2(int n) {
List<String> res = new ArrayList<>();
if(n <= 0) {
return res;
}
dfs(res, "", n , n);
return res;
}