数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
提示:
1 <= n <= 8
class Solution {
static List<String> res = new ArrayList<String>(); //记录答案
public List<String> generateParenthesis(int n) {
res.clear();
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 < n && lc > rc) dfs(n, lc, rc + 1, str + ")"); //拼接右括号
}
}
}