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:
"((()))", "(()())", "(())()", "()(())", "()()()"
思路:使用递归方法,
规则是:
a. '('没加完,就可以加'(',
b. ')'加入需要满足两点:1.')'没加完;
2. 剩余'('数小于剩余')'数,加上')'才能保证可能匹配
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
String s = "";
int left = n;
int right = n;
generate(left, right, s, result);
return result;
}
private void generate(int left, int right, String s, List<String> result) {
if (left == 0 && right == 0) {
result.add(s);
}
if (left > 0) {
generate(left - 1, right, s + "(", result);
}
if (right > 0 && left < right) {
generate(left, right - 1, s + ")", result);
}
}
}