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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
backtracking的问题
结束递归的条件是有2n个括号
首先进入递归的是n个正括号
然后是n个反括号
要求反括号的数量小于等于正括号的时候才进入递归即可
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
String tmp = "";
helper(result, tmp, 0, 0, n);
return result;
}
private void helper(List<String> result, String tmp, int pre, int pos, int n){
if(tmp.length() == n * 2){
result.add(tmp);
return;
}
if(pre < n){
helper(result, tmp + "(", pre + 1, pos, n);
}
if(pos < pre){
helper(result, tmp + ")", pre, pos + 1, n);
}
}
}