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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路:递归解,用left和right分别表示左右括号的数量,在递归的过程中,判断左右括号数量间不同的关系来决定early stop或者是继续递归或者是返回result。注意,参数用stringbuilder会比string快,用char[index]会比strinbuilder快!
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
if (n == 0) return result;
return helper(n, 0, 0, result, new StringBuilder());
}
public List<String> helper(int n, int left, int right, List<String> result, StringBuilder cur) {
if (left < right || left > n || right > n) return result;
if (left == right && left == n) {
result.add(new String(cur.toString()));
return result;
}
int size = cur.length();
helper(n, left + 1, right, result, cur.append("("));
cur.setLength(size);
helper(n, left, right + 1, result, cur.append(")"));
cur.setLength(size);
return result;
}