classSolution{List<String> res =newLinkedList<>();publicList<String>generateParenthesis(int n){String str ="";int first =0,second =0;backtrack(str,first,second,n);return res;}voidbacktrack(String str,int first,int second,int n){if(first == n && second == n ){
res.add(newString(str));return;}for(int i =0;i <2;++i){if(first != n && i ==0){
str +="(";
first++;}elseif(first !=0&& first > second && i ==1){
str +=")";
second++;}else{continue;}backtrack(str,first,second,n);if(i ==0){
str = str.substring(0,str.length()-1);
first--;}else{
str = str.substring(0,str.length()-1);
second--;}}}}
算法回溯法核心思想简单的回溯,这几天做了几个回溯的类型题,简单做个总结,不一定对,还需要验证:使用回溯的题目,基本和二叉树和图有关系,使用的方法很多事深度优先遍历。对于二叉树的题目做好画好一个二叉树,做好模拟,想好减枝的条件,操作即可。代码class Solution { List<String> res = new LinkedList<>(); public List<String> generateParenthesis(int n).