使用了遞歸回溯:
public static List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
helper(res,"",0,0,n);
return res;
}
public static void helper(List<String> res,String out,int open,int close,int n) {
if(out.length() == 2*n) {
res.add(out);
return;
}
if(open < n) {
helper(res,out+"(",open+1,close,n);
}
if(close < open) {
helper(res,out+")",open,close+1,n);
}
}