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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
String paren = "";
helper(result,paren, n, n);
return result;
}
private void helper(List<String> result, String paren,int left, int right) {
if (left == 0 && right == 0) {
result.add(paren);
return;
}
if (left > 0) {
helper(result, paren + "(", left - 1, right);
}
if (right > 0 && left < right) {
helper(result, paren + ")", left, right - 1);
}
}
}
Java2
class Solution {
List<String> ans = new LinkedList<>();
public List<String> generateParenthesis(int n) {
buildCombo("", n, 0, 0, 0);
return ans;
}
private void buildCombo(String s, int n, int close, int open, int totalPlaced) {
if(totalPlaced == n * 2) {
ans.add(s);
} else {
if (open < n) {
buildCombo(s + "(", n, close, open + 1, totalPlaced + 1);
}
if (close < open) {
buildCombo(s + ")", n, close + 1, open, totalPlaced + 1);
}
}
}
}
class Solution {
List<String> res = new ArrayList<>();
public List<String> generateParenthesis(int n) {
dfs("",0,0,n);
return res;
}
void dfs(String s , int open, int close, int total) {
if(open+close == total<<1) { //total*2
res.add(s);
return;
}
if(open<total)
dfs(s+"(",open+1,close,total);
if(close<open)
dfs(s+")",open, close+1, total);
}
}
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 0:
return []
elif n == 1:
return ["()"]
else:
pairs = set()
for word in self.generateParenthesis(n-1):
for i in range(0, len(word)):
pairs.add(word[:i] + "()" + word[i:])
return pairs
class Solution {
public List<String> generateParenthesis(int n) {
if (n == 0) return new ArrayList<String>();
List<String> result = new ArrayList<>();
int open = 0, close = 0;
generateParenthesis(result, new StringBuilder(), open, close, n);
return result;
}
public static void generateParenthesis(List<String> result, StringBuilder temp, int open, int close, int n) {
if (temp.length() == 2 * n) {
result.add(temp.toString());
return;
}
if (open < n) {
//add open brace
int size = temp.length();
temp.append("(");
generateParenthesis(result, temp, open + 1, close, n);
temp.setLength(size);
}
if (close < open) {
//add close brace
int size = temp.length();
temp.append(")");
generateParenthesis(result, temp, open, close + 1, n);
temp.setLength(size);
}
}
}