Generate Parentheses
Build every well-formed string of n pairs of brackets by adding one bracket at a time.
Given a number nn(n)())(
Example 1
Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]
Example 2
Output: ["()"]
The Idea
Brackets in a sum on paper follow a rule you already know: (2 + 3) * (4 - 1))2 + 3( * 4n
With one pair there is one answer, ()(())()()()
So writing every string and checking it afterwards throws away most of the work. Can we tell, while writing a string from left to right, that it has already gone wrong?
We can, by counting as we write: how many ()(n)()
Look at the picture below. It writes the strings for n = 2
The dashed orange boxes break one of the two counting rules, so the search stops there. From the empty box, add ) leads to )((
Follow the left side down. After (())(()()()
Notice that every blue box in the picture leads down to a teal answer. The two counts cut a branch the moment it breaks a rule, so the search never wanders down a path that ends nowhere.
Solution Approach
Writing every string and keeping the balanced ones is the plain way, and it is slow. The faster way needs three decisions: which bracket may come next, how to take a bracket back, and when a string is complete.
Trying every string
Why not write all the strings of 2n2nn = 8
Which bracket may come next
What decides the next character? The two counts: how many ()openclose(open < n)close < open(n = 2()
Why does a string that obeys both rules always end balanced? closeopenopenn2n2nn
Taking a bracket back
How does the search move between boxes? A method named build
All the calls share one StringBuildersbsbdeleteCharAtsb
When a string is complete
When does a branch stop with an answer? When sb2nnsb.toString()
Java Solution
The method generateParenthesis
- First, create the list
for the answers and an emptyresult namedStringBuilder , and callsb withbuild andopen both at 0.close - Inside
, check the length ofbuild . If it issb , add a copy of it to2 * n and return.result - If
, appendopen < n , call'(' withbuild , and then remove the last character withopen + 1 .deleteCharAt - If
, do the same withclose < open and')' .close + 1 - When the first call to
returns, every branch has been tried, andbuild returnsgenerateParenthesis .result
The mainn = 2n
import java.util.ArrayList;
import java.util.List;
public class GenerateParentheses {
public static List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
build(n, 0, 0, new StringBuilder(), result);
return result;
}
private static void build(int n, int open, int close, StringBuilder sb, List<String> result) {
if (sb.length() == 2 * n) {
result.add(sb.toString()); // all n pairs placed: one answer
return;
}
if (open < n) { // an opening bracket is still left
sb.append('(');
build(n, open + 1, close, sb, result);
sb.deleteCharAt(sb.length() - 1); // take it back before the next choice
}
if (close < open) { // some bracket is open and can be closed
sb.append(')');
build(n, open, close + 1, sb, result);
sb.deleteCharAt(sb.length() - 1);
}
}
public static void main(String[] args) {
System.out.println(generateParenthesis(3));
System.out.println(generateParenthesis(1));
System.out.println(generateParenthesis(2));
for (int n = 1; n <= 8; n++) {
System.out.print(generateParenthesis(n).size() + (n < 8 ? " " : "\n"));
}
}
}
Running it prints:
[((())), (()()), (())(), ()(()), ()()()]
[()]
[(()), ()()]
1 2 5 14 42 132 429 1430
The third line, [(()), ()()]build()((()))n = 3
The last line counts the answers for n2nbuildn = 3
The second rule is easy to write wrongly as close < n)(n = 2(())()()())()(())()())((
Complexity
The work depends on how many answers there are, because every box the search writes leads to at least one of them. For nn
- Time: O(Cn · n), because each of the Cn answers ends a path of 2n + 1 calls and takes O(n) to copy, and Cn grows roughly like 4n / n1.5.
- Space: O(n) besides the answers, because the calls nest at most 2n + 1 deep, one per bracket plus the first, and
holds at most 2n characters.sb