Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
public class Solution { /** * 也可以参考http://blog.csdn.net/u011095253/article/details/9158429的第二种方法 **/ public ArrayList<String> generateParenthesis(int n) { if (n<=0) { return new ArrayList<String>(); } if (n==1) { ArrayList<String> ret = new ArrayList<String>(); ret.add("()"); return ret; } ArrayList<String> ret = generateParenthesis(n-1); HashSet<String> ret2 = new HashSet<String>(); for (String temp : ret) { ret2.add("("+temp+")"); ret2.add("()"+temp); ret2.add(temp+"()"); //fix result (())(()) for (int j=0;j<temp.length();j++) { if (temp.charAt(j) == '(') { String fix = temp.substring(0, j+1) + "()" + temp.substring(j+1); ret2.add(fix); } } } ret.clear(); for (String s:ret2) { ret.add(s); } return ret; } }