解题思路
做括号这一类型的题应该记住两个结论,
1 在这字符串的前缀中,左括号的数量大于等于右括号的数量。
当添加左括号的数量大于右括号的数量,此时可以添加右括号。
2 左括号,右括号的数量分别不超过n。
相关代码
class Solution {
List<String> res = new ArrayList<>();
String path="";
public List<String> generateParenthesis(int n) {
dfs(0,0,n,path);
return res;
}
public void dfs(int l,int r,int n,String path){
if(l==n&&r==n){
res.add(new String(path));
return;
}
if(l<n){
String temp =path;
path = path+'(';
dfs(l+1,r,n,path);
path = temp;
}
if(r<n&&l>r){
String temp =path;
path = path+')';
dfs(l,r+1,n,path);
path = temp;
}
}
}