题目:https://leetcode-cn.com/problems/generate-parentheses/
答案:
1.深度搜索
左边括号必须大于或等于右边括号
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
if(n<=0) return result;
dfs("",n,n,result);
return result;
}
public void dfs(String string,int left,int right,List<String> result){
if(left==0 && right == 0) {
result.add(string);
return;
}
if(left>right) return;
if(left>0){
dfs(string+"(",left-1,right, result);
}
if(right>0){
dfs(string+")", left, right-1,result);
}
}
2、回溯法:
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
if(n<=0) return result;
dfs(new StringBuilder(),n,n,result);
return result;
}
public void dfs(StringBuilder string,int left,int right,List<String> result){
if(left==0 && right == 0) {
result.add(string.toString());
return;
}
if(left>right) return;
if(left>0){
string.append("(");
dfs(string,left-1,right, result);
string.deleteCharAt(string.length()-1);
}
if(right>0){
string.append(")");
dfs(string, left, right-1,result);
string.deleteCharAt(string.length()-1);
}
}