Last active
January 1, 2016 11:49
-
-
Save beeflamian/8140353 to your computer and use it in GitHub Desktop.
generating parentheses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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