Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created November 8, 2017 15:55
Show Gist options
  • Select an option

  • Save shailrshah/77b801a98be6f44692c50f68213bf8de to your computer and use it in GitHub Desktop.

Select an option

Save shailrshah/77b801a98be6f44692c50f68213bf8de to your computer and use it in GitHub Desktop.
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<>();
backtrack(list, new StringBuilder(), 0, 0, n);
return list;
}
private static void backtrack(List<String> list, StringBuilder sb, int open, int close, int n) {
if(sb.length() == 2*n){
list.add(sb.toString());
return;
}
if(open < n){
sb.append("(");
backtrack(list, sb, open+1, close, n);
sb.setLength(sb.length() - 1);
}
if(close < open){
sb.append(")");
backtrack(list, sb, open, close+1, n);
sb.setLength(sb.length() - 1);
}
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment