For example, given n = 3, a solution set is:app
"((()))", "(()())", "(())()", "()(())", "()()()"
ui
public class Solution {
private ArrayList<String> array;
private int count;
private int number;
public ArrayList<String> generateParenthesis(int n) {
array = new ArrayList<String>();
number = n;
StringBuilder s = new StringBuilder();//"(";
s.append('(');
recurse(s, 1, 0);
return array;
}
private void recurse(StringBuilder s, int leftTotal, int rightTotal){
if(leftTotal == number){
int total = 2*number;
StringBuilder sb = new StringBuilder(total);
for(int i = 0; i < s.length(); i++){
sb.append(s.charAt(i));
}
while(sb.length() < total){
sb.append(')');
}
count++;
array.add(sb.toString());
return;
}
if(leftTotal > rightTotal){
recurse(s.append(')'), leftTotal, rightTotal+1);
s.deleteCharAt(s.length()-1);
}
recurse(s.append('('), leftTotal+1, rightTotal);
s.deleteCharAt(s.length()-1);
}
}spa