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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Subscribe to see which companies asked this question
public class Solution {
public void generateParenthesisAux(int n, int k, int i, char[] path, List res){
if(0 == k){
// no more left parenthesis
for( int l = i; l < n*2; ++l){
path[l] = ')';
}
res.add(new String(path));
}else{
path[i] = '(';
generateParenthesisAux(n, k-1, i+1, path, res);
if((n - k) * 2 > i){
path[i] = ')';
generateParenthesisAux(n, k, i+1, path, res);
}
}
return;
}
public List generateParenthesis(int n) {
ArrayList res = new ArrayList();
generateParenthesisAux(n, n, 0, new char[2*n], res);
return res;
}
}
No comments:
Post a Comment