Skip to content

Instantly share code, notes, and snippets.

@beeflamian
Last active January 1, 2016 11:49
Show Gist options
  • Save beeflamian/8140353 to your computer and use it in GitHub Desktop.
Save beeflamian/8140353 to your computer and use it in GitHub Desktop.
generating parentheses
public ArrayList<String> generateParenthesis(int n) {
String left = "";
String right = "";
ArrayList<String> res = new ArrayList<String>();
String oneSolu = "";
for (int i=0; i<n; i++) {
left += "(";
right += ")";
}
Generate(n, n, res, oneSolu);
return res;
}
private void Generate(int l, int r, ArrayList<String> res, String oneSolu) {
if (l==0 && r==0) {
res.add(oneSolu);
return ;
}
//add left
if (l > 0) {
String t = oneSolu;
t += "(";
Generate(l-1, r, res, t);
}
if (r>l) {
String t = oneSolu;
t += ")";
Generate(l, r-1, res, t);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment