Created
November 8, 2017 15:55
-
-
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.
This file contains hidden or 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 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