Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
Java Solution 1 – DFS
This solution is simple and clear. In the dfs() method, left stands for the remaining number of (, right stands for the remaining number of ).
public List<String> generateParenthesis(int n) { ArrayList<String> result = new ArrayList<String>(); dfs(result, "", n, n); return result; } /* left and right represents the remaining number of ( and ) that need to be added. When left > right, there are more ")" placed than "(". Such cases are wrong and the method stops. */ public void dfs(ArrayList<String> result, String s, int left, int right){ if(left > right) return; if(left==0&&right==0){ result.add(s); return; } if(left>0){ dfs(result, s+"(", left-1, right); } if(right>0){ dfs(result, s+")", left, right-1); } } |
Java Solution 2
This solution looks more complicated. ,You can use n=2 to walk though the code.
public List<String> generateParenthesis(int n) { ArrayList<String> result = new ArrayList<String>(); ArrayList<Integer> diff = new ArrayList<Integer>(); result.add(""); diff.add(0); for (int i = 0; i < 2 * n; i++) { ArrayList<String> temp1 = new ArrayList<String>(); ArrayList<Integer> temp2 = new ArrayList<Integer>(); for (int j = 0; j < result.size(); j++) { String s = result.get(j); int k = diff.get(j); if (i < 2 * n - 1) { temp1.add(s + "("); temp2.add(k + 1); } if (k > 0 && i < 2 * n - 1 || k == 1 && i == 2 * n - 1) { temp1.add(s + ")"); temp2.add(k - 1); } } result = new ArrayList<String>(temp1); diff = new ArrayList<Integer>(temp2); } return result; } |
PROBLEM: GIVEN N PAIRS OF PARENTHESES, WRITE A FUNCTION TO GENERATE ALL COMBINATIONS OF WELL-FORMED PARENTHESES.
SOLUTION: https://youtu.be/u_Zmx9cLHjk
INPUT: N = 3
OUTPUT: [“((()))”,”(()())”,”(())()”,”()(())”,”()()()”]
Hi Guys
I made small video explaining the solution using recursion, please check this out
https://www.youtube.com/watch?v=0_2uuS97YYg
Catalan number of ways !!
Great analysis. If you want to see another insightful discussion with code, check https://goo.gl/ALZBh0.
Your solution doesnt work….it fails for n=4 for this case “(())(())”
Whats the time complexity of solution 1 ?
Want to share my very simple recursive solution on C#:
“class Parenthesis”
“{”
” private List result = new List();””
” public List Generate(int n)”
” {”
” if (n <= 0)"
" throw new ArgumentException();"
” Generate(n, 0, 0, “”);”
” return this.result;”
” }”
” private void Generate(int n, int opened, int closed, string print)”
” {”
” if (opened < n)"
" Generate(n, opened + 1, closed, print + "(");"
” if (closed < opened)"
" Generate(n, opened, closed + 1, print + ")");"
” if (opened == closed && opened == n)”
” this.result.Add(print);”
” }”
“}”
X(n+1) = { ()[X(n)] } X(n+1) = X(n) + 2
X(n) = 2n – 1
Another approach I came up with that does not require to keep track of the opening or closing tags is as follows. It does generate the same solution multiple times however.
public static Set generateParentheses(int n, boolean print)
{
Set solutions = new HashSet();
//Case n=0 generates the empty set.
if(n > 0)
{
//Case n=1, which adds the first solution.
solutions.add(“()”);
}
//This loop start with n=2
for(int i=2; i<=n; i++)
{
Set newSolutions = new HashSet();
//Loop through the combinations obtained in the previous step
for(String previousSolution : solutions)
{
newSolutions.add(“()” + previousSolution);
newSolutions.add(“(” + previousSolution + “)”);
newSolutions.add(previousSolution + “()”);
}
solutions = newSolutions;
}
return solutions;
}
how to calculate the time complexity of this algorithm?