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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
[code]
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> list=new ArrayList<String>();
if(n<=0)return list;
StringBuffer path=new StringBuffer();
dfs(0, 0, n, path ,list);
return list;
}
void dfs(int left, int right, int n, StringBuffer path, List<String> list)
{
if(left<right || left>n)return;
if(left==right && left==n)
{
list.add(path.toString());
return;
}
path.append('(');
dfs(left+1, right, n, path, list);
path.deleteCharAt(path.length()-1);
path.append(')');
dfs(left, right+1, n, path, list);
path.deleteCharAt(path.length()-1);
}
}