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 ArrayList<String> generateParenthesis(int n) {
ArrayList<String> res = new ArrayList<String>();
backtracking(n, n, "", res);
return res;
}
public void backtracking(int left, int right, String str, ArrayList<String> res) {
if (left == 0 && right == 0) {
res.add(str);
return;
}
if (left > 0) {
backtracking(left - 1, right, str + '(', res);
}
if (right > left) {
backtracking(left, right - 1, str + ')', res);
}
}
The idea here is to only add ‘(’ and ‘)’ that we know will guarantee us a solution (instead of adding 1 too many close). Once we add a ‘(’ we will then discard it and try a ‘)’ which can only close a valid ‘(’. Each of these steps are recursively called.
一定是‘(’在前 而且在添加过程中‘(’的个数不能少于‘)’的个数