题干
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:
输入:n = 3
输出:[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
想法
这道题难点就是
给定n,
只有在没有匹配的右括号数大于左括号的时候才能加上右括号,因为左括号总在前边
所以递归就好了
因为右括号不会更多且不会首先出现,所以一定是匹配的
Java代码
package daily;
import java.util.*;
public class GenerateParenthesis {
public List<String> generateParenthesis(int n) {
//res存储结果
List<String> res=new ArrayList<>();
dfs(n,n,"",res);
return res;
}
//dfs递归函数
private void dfs(int left,int right,String str,List<String> res){
//左右都没了 加入res
if(left==0&&right==0){
res.add(str);
return;
}
//还有左括号没有加 那就加
if(left>0){
dfs(left-1,right,str+"(",res);
}
//右括号一定在左括号后
if(right>left){
dfs(left,right-1,str+")",res);
}
}
public static void main(String[] args){
GenerateParenthesis generateParenthesis=new GenerateParenthesis();
System.out.println(generateParenthesis.generateParenthesis(3));
}
}