https://leetcode.com/problems/generate-parentheses/#/description
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
package go.jacob.day719;
import java.util.ArrayList;
import java.util.List;
public class Demo3 {
List<String> res;
public List<String> generateParenthesis(int n) {
res = new ArrayList<String>();
if (n <= 0)
return res;
generateParenthesis(n, "(", 2, 1);
return res;
}
private void generateParenthesis(int n, String str, int left, int right) {
//终止条件
if (left > n && right > n) {
res.add(str);
return;
}
if (left > n)
generateParenthesis(n, str + ")", left, right + 1);
//左括号和右括号小用户最大值
else if (right < left) {
generateParenthesis(n, str + "(", left + 1, right);
generateParenthesis(n, str + ")", left, right + 1);
} else if (right == left)
generateParenthesis(n, str + "(", left + 1, right);
}
}