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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]思路:
深度优先算法。
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
if (n <= 0)
return res;
String bracket = "";
dfs(res, bracket, n, n);
return res;
}
private void dfs(List<String> res, String bracket, int left,
int right) {
if(left > right){
return;
}
if (left == 0 && right == 0) {
res.add(bracket);
return;
}
if (left > 0) {
dfs(res, bracket + "(", left - 1, right);
}
if (right > 0) {
dfs(res, bracket + ")", left, right - 1);
}
}
}