![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/63c0a01de5e297352ae3831001b7a3d8.png)
暴力法
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e75425a87b5d17cb6c0375c92a771866.png)
class Solution {
List<String> data=new ArrayList<String>();
public List<String> generateParenthesis(int n) {
char[] ch=new char[2*n];
generateAll(ch,0);
return data;
}
void generateAll(char[] ch,int pos){
if(pos==ch.length){
if(isvaild(ch)){
data.add(new String(ch));
}
}
else{
ch[pos]='(';
generateAll(ch,pos+1);
ch[pos]=')';
generateAll(ch,pos+1);
}
}
boolean isvaild(char[] ch){
int balance=0;
for(int i=0;i<ch.length;i++){
if(ch[i]=='('){
balance++;
}
if(ch[i]==')'){
balance--;
}
if(balance<0){
return false;
}
}
return balance==0?true:false;
}
}
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 curStr) {
if (left == 0 && right == 0) {
res.add(curStr);
return;
}
if (left > 0) {
dfs(left - 1, right, curStr + "(");
}
if (right > left) {
dfs(left, right - 1, curStr + ")");
}
}
}