Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
在做这道题时,在字符串如何生成时,思考了许久无果,还是对数据结构没有深刻领悟,于是查了资料,发现可以类似于二叉树的做法。
如下图,借鉴于别人
代码如下
public static List<String> generateParenthesis(int n) {
String s ="";
List<String> list = new ArrayList<String>();
leaf(list,n, n, s);
return list;
}
public static void leaf(List<String> list,int left,int right,String leaf){
if(left == 0 && right == 0){
list.add(leaf);
return ;
}
if(left != 0){
leaf(list, left - 1, right ,leaf + '(');
}
if(right != 0 && left < right){
leaf(list, left, right - 1 ,leaf + ')');
}
}