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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]递归的思路,如果“(”的数量小于n,先添加一个“(”,如果“)”的数量小于“(”的数量,则再添加一个“)”,如果“(”和“)”的数量都等于n那么把这个组合方式加入到结果中。代码如下:
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
helper(res, new StringBuilder(), 0, 0, n);
return res;
}
private void helper(List<String> list, StringBuilder sb, int open, int close, int n) {
if (open == n && close == n) {
list.add(sb.toString());
return;
}
if (open < n) {
sb.append("(");
helper(list, sb, open + 1, close, n);
sb.setLength(sb.length() - 1);
}
if (close < open) {
sb.append(")");
helper(list, sb, open, close + 1, n);
sb.setLength(sb.length() - 1);
}
}
}