Skip to content

Instantly share code, notes, and snippets.

@cangoal
Last active March 17, 2016 17:49
Show Gist options
  • Save cangoal/af447290c3e6538cefef to your computer and use it in GitHub Desktop.
Save cangoal/af447290c3e6538cefef to your computer and use it in GitHub Desktop.
LeetCode - Generate Parentheses
// Using String
public List<String> generateParenthesis(int n) {
ArrayList<String> ret = new ArrayList<String>();
if(n<1) return ret;
String str = "";
helper(n,n,ret, str);
return ret;
}
private void helper(int left, int right, ArrayList<String> ret, String str){
if(left==0 && right==0){
ret.add(str);
}
if(left>right) return;
if(left>0){
helper(left-1, right, ret, str+"(");
}
if(right>0){
helper(left, right-1, ret, str+")");
}
}
// Using StringBuilder
public List<String> generateParenthesis(int n) {
ArrayList<String> ret = new ArrayList<>();
if(n < 0) return ret;
helper(ret, n, n, new StringBuilder());
return ret;
}
public void helper(ArrayList<String> ret, int left, int right, StringBuilder sb){
if(left == right && left == 0){
ret.add(sb.toString());
return;
}
if(left > 0){
sb.append('(');
helper(ret, left-1, right, sb);
sb.deleteCharAt(sb.length()-1);
}
if(right > left){
sb.append(')');
helper(ret, left, right-1, sb);
sb.deleteCharAt(sb.length()-1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment