数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入: n = 3
输出: ["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入: n = 1
输出: ["()"]
提示:
1 <= n <= 8
题解:
class Solution {
List<String>result=new ArrayList<>();
public List<String> generateParenthesis(int n) {
if(n==0) return result;
//回溯法
String res="";
dfs(0,0,n,res);
return result;
}
public void dfs(int numleft,int numright,int n,String res){
if(numleft>n||numright>n||numright>numleft) return;
if(numright==numleft&&numleft==n)
result.add(res);
else if(numleft==n)
dfs(numleft,numright+1,n,res+")");
else{
dfs(numleft+1,numright,n,res+"(");
dfs(numleft,numright+1,n,res+")");
}
}
}