Question
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:
"((()))", "(()())", "(())()", "()(())", "()()()
Solution 1
Two conditions to check:
if remained left '(' nums < remained right ')', for next char, we can put '(' or ')'.
if remained left '(' nums = remained right ')', for next char, we can only put '('.
Draw out the solution tree, and do DFS.
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
List<Character> list = new ArrayList<Character>();
dfs(n, n, list, result);
return result;
} private void dfs(int leftRemain, int rightRemain, List<Character> list, List<String> result) {
if (leftRemain < 0 || rightRemain < 0 || leftRemain > rightRemain)
return; if (leftRemain == 0 && rightRemain == 0) {
int size = list.size();
StringBuilder sb = new StringBuilder(size);
for (char tmpChar : list)
sb.append(tmpChar);
result.add(sb.toString());
return;
} if (leftRemain == rightRemain) {
list.add('(');
dfs(leftRemain - 1, rightRemain, list, result);
list.remove(list.size() - 1);
} else {
list.add(')');
dfs(leftRemain, rightRemain - 1, list, result);
list.remove(list.size() - 1);
list.add('(');
dfs(leftRemain - 1, rightRemain, list, result);
list.remove(list.size() - 1);
}
}
}
Solution 2
A much simpler solution.
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
List<Character> list = new ArrayList<Character>();
dfs(n, n, "", result);
return result;
} private void dfs(int leftRemain, int rightRemain, String prefix, List<String> result) {
if (leftRemain < 0 || rightRemain < 0 || leftRemain > rightRemain)
return;
if (leftRemain == 0 && rightRemain == 0) {
result.add(new String(prefix));
return;
}
if (leftRemain > 0)
dfs(leftRemain - 1, rightRemain, prefix + "(", result);
if (rightRemain > 0)
dfs(leftRemain, rightRemain - 1, prefix + ")", result);
}
}