# LeetCode 22. Generate Parentheses（生成括号）

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 void find(int remain, int left, int right, char[] parenthesis, List<String> results) {
if (remain == 0) {
return;
}
if (left + 1 <= parenthesis.length/2) {
parenthesis[parenthesis.length - remain] = '(';
find(remain-1, left+1, right, parenthesis, results);
}
if (right + 1 <= parenthesis.length/2 && right < left) {
parenthesis[parenthesis.length - remain] = ')';
find(remain-1, left, right+1, parenthesis, results);
}
}
public List<String> generateParenthesis(int n) {
List<String> results = new ArrayList<>();
find(n*2, 0, 0, new char[n*2], results);
return results;
}
}

public class Solution {
private void find(char[] p, int len, int left, int right, List<String> results) {
if (len == p.length) {
return;
}
if (left<p.length/2) {
p[len] = '(';
find(p, len+1, left+1, right, results);
}
if (left>right) {
p[len] = ')';
find(p, len+1, left, right+1, results);
}
}
public List<String> generateParenthesis(int n) {
List<String> results = new ArrayList<>();
find(new char[n*2], 0, 0, 0, results);
return results;
}
}