classSolution{public List<String>generateParenthesis(int n){
List<String> list =newArrayList<String>();generate(list,0,0, n,"");return list;}privatevoidgenerate(List<String> list,int left,int right,int n, String s){//terminatorif(left == n && right == n){
list.add(s);return;}//process current logic: left, right//drill downif(left < n){generate(list, left +1, right, n, s +"(");}if(right < left){generate(list, left, right +1, n, s +")");}//reverse states;}}
classSolution{//做加法public List<String>generateParenthesis(int n){
List<String> res =newArrayList<>();//特判if(n ==0){return res;}dfs("",0,0, n, res);return res;}privatevoiddfs(String curStr,int left,int right,int n, List<String> res){//terminatorif(left == n && right == n){
res.add(curStr);return;}//process current logic: left, right//剪枝// if (left < right) {// return;// }//drill downif(left < n){dfs(curStr +"(", left +1, right, n, res);}if(right < left){dfs(curStr +")", left, right +1, n, res);}//reverse states;//由于字符串的特殊性,产生一次拼接都生成新的对象,因此无需回溯}}
classSolution{//做减法public List<String>generateParenthesis(int n){
List<String> res =newArrayList<>();//特判if(n ==0){return res;}dfs("", n, n, res);return res;}privatevoiddfs(String curStr,int left,int right, List<String> res){//terminatorif(left ==0&& right ==0){
res.add(curStr);return;}//process current logic: left, right//剪枝// if (left > right) {// return;// }//drill downif(left >0){dfs(curStr +"(", left -1, right, res);}if(right > left){dfs(curStr +")", left, right -1, res);}//reverse states;//由于字符串的特殊性,产生一次拼接都生成新的对象,因此无需回溯}}