Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: [“((()))”,”(()())”,”(())()”,”()(())”,”()()()”]
Example 2:
Input: n = 1
Output: [“()”]
Constraints:
1 <= n <= 8
Solution
- The idea is to add
')'
only after valid'('
- We use two integer variables
left
&right
to see how many'('
&')'
are in the current string - If
left < n
then we can add'('
to the current string - If
right < left
then we can add')'
to the current string
Python Code
def generateParenthesis(self, n: int) -> List[str]:
def dfs(left, right, s):
if len(s) == n * 2:
res.append(s)
return
if left < n:
dfs(left + 1, right, s + '(')
if right < left:
dfs(left, right + 1, s + ')')
res = []
dfs(0, 0, '')
return res
Java Code
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
recurse(res, 0, 0, "", n);
return res;
}
public void recurse(List<String> res, int left, int right, String s, int n) {
if (s.length() == n * 2) {
res.add(s);
return;
}
if (left < n) {
recurse(res, left + 1, right, s + "(", n);
}
if (right < left) {
recurse(res, left, right + 1, s + ")", n);
}
}
// See above tree diagram with parameters (left, right, s) for better understanding
}
C++
class Solution {
public:
void solve(string op, int open, int close, vector<string> &ans){
if(open == 0 && close == 0){
ans.push_back(op);
return;
}
//when count of open and close brackets are same then
//we have only one choice to put open bracket
if(open == close){
string op1 = op;
op1.push_back('(');
solve(op1, open-1, close, ans);
}
else if(open == 0){
//only choice is to put close brackets
string op1 = op;
op1.push_back(')');
solve(op1, open, close-1, ans);
}
else if(close == 0){
//only choise is to use open bracket
string op1 = op;
op1.push_back('(');
solve(op1, open-1, close, ans);
}
else{
string op1 = op;
string op2 = op;
op1.push_back('(');
op2.push_back(')');
solve(op1, open-1, close, ans);
solve(op2, open, close-1, ans);
}
}
vector<string> generateParenthesis(int n) {
int open = n;
int close = n;
vector<string> ans;
string op = "";
solve(op, open, close, ans);
return ans;
}
};
Javascript
const generateParenthesis = (n) => {
const res = [];
const go = (l, r, s) => { // l: left remaining, r: right remaining
if (l > r) return; // Validate by the number of '(' should be always >= ')'
if (l === 0 && r === 0) {
res.push(s);
return;
}
if (l > 0) go(l - 1, r, s + '(');
if (r > 0) go(l, r - 1, s + ')');
};
go(n, n, '');
return res;
};