





class Solution {
List<String> res = new ArrayList<>();
public List<String> generateParenthesis(int n) {
dfs(n, 0, 0, "");
return res;
}
public void dfs(int n, int lc, int rc, String str){
if(lc == n && rc == n){
res.add(str);
}
else{
if(lc < n){
dfs(n, lc + 1, rc, str + "(");
}
if(rc < lc && rc < n){
dfs(n, lc ,rc + 1, str + ")");
}
}
}
}
这篇文章介绍了一个使用深度优先搜索(DFS)算法解决的问题,即给定整数n,生成所有有效的n对括号组合。通过递归函数`dfs`实现,当左右括号数量相等时将结果添加到结果列表中。
471

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



