所有题目源代码:Git地址
题目
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:
输入:n = 3
输出:[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
方案:根据题意判断,应当是用DFS做
class Solution {
List<String> res = new ArrayList<>();
public List<String> generateParenthesis(int n) {
dfs(n, n, "");
return res;
}
private void dfs(int left, int right, String s) {
if (left==0&&right==0){
res.add(s);
}
else {
if (left>0){
dfs(left-1,right,s+"(");
}if (right>left){
dfs(left,right-1,s+")");
}
}
}
}
复杂度计算
- 时间复杂度:O(n)
- 空间复杂度:O(n)