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 List<String> generateParenthesis(int n) { List<String> result = new ArrayList<String>(); gen(n, n, "", result); return result; } private void gen(int l, int r, String current, List<String> result) { if(l == 0 && r == 0) { result.add(current); } if(l <= r) { if(l > 0) gen(l-1, r, current+"(", result); if(r > 0) gen(l, r-1, current+")", result); } }
没有评论:
发表评论