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 class GenerateParentheses {
public List<String> generateParentheses(int n){
List<String> ans = new ArrayList<String>();
backTrack(ans,"",0,0,n);
return ans;
}
private void backTrack(List<String> ans, String str, int open, int close, int n) {
if(str.length() == 2*n){//生成一个符合条件的串
ans.add(str);//加入list中
return;//返回当前递归
}
if(open < n){
backTrack(ans, str+"(", open+1, close, n);//使用递归调用
}
if(close < open){//注意是close<open,保持“(”在“)”的前面
backTrack(ans,str+")",open,close+1,n);
}
}
}