题目描述
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:
输入:n = 3
输出:[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
题解
DFS(java)
比较经典的dfs解法,比起全部遍历添加了两个剪枝条件。
class Solution {
List<String> ans = new LinkedList<>();
public void dfs(int left, int right, String s , int n) {
if (s.length() == n * 2) {
ans.add(s);
}
if (left < n) {
dfs(left + 1, right, s + "(", n);
}
if (right < left) {
dfs(left, right + 1, s + ")", n);
}
}
public List<String> generateParenthesis(int n) {
dfs(0, 0, "", n);
return ans;
}
复杂度分析
- 时间复杂度: O ( 4 n n ) O(\frac{4^n}{\sqrt{n}}) O(n4n) , 该复杂度为第n个卡特兰数
- 空间复杂度: O ( n ) O(n) O(n) ,取决于递归栈的深度,最深为2n层
DFS2(java)
DFS搜索所有可能的组合情况,在添加在最后的输出列表之前对其有效性做检查。
trick: 在递归时可以使用char数组,方便遍历检查有效性;在最后输出时用new String(current) 直接构造新字符串。
class Solution {
public List<String> generateParenthesis(int n) {
List<String> combinations = new ArrayList();
generateAll(new char[2 * n], 0, combinations);
return combinations;
}
public void generateAll(char[] current, int pos, List<String> result) {
if (pos == current.length) {
if (valid(current))
result.add(new String(current));
} else {
current[pos] = '(';
generateAll(current, pos+1, result);
current[pos] = ')';
generateAll(current, pos+1, result);
}
}
public boolean valid(char[] current) {
int balance = 0;
for (char c: current) {
if (c == '(') balance++;
else balance--;
if (balance < 0) return false;
}
return (balance == 0);
}
}
- 时间复杂度: O ( 2 2 n n ) O(2^{2n}n) O(22nn)
- 空间复杂度: O ( n ) O(n) O(n)
629

被折叠的 条评论
为什么被折叠?



