# (Java)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 {

List<?>[] ans = new ArrayList<?>[100];
boolean flag = false;
int N = 1;
public List<String> generateParenthesis(int n) {
if(n <= N){
if( n == 1 && flag == false){
List<String> list = new ArrayList<String>();
ans[N++] = list;
flag = true;
return list;
}
else
return (List<String>)ans[n];
}
Set<String> set = new HashSet<String>();
for(int i = 0 ; i < n ; i++){
if(i == 0){
for(String ss : generateParenthesis(n-1)){
}
}else{
for(String ss : generateParenthesis(i)){
for(String aa : generateParenthesis(n-i)){
}
}
}
}
if(N == n){
ans[N++] = new ArrayList<String>(set);
}
return new ArrayList<String>(set);
}

public static void main(String[] args){
Solution sol = new Solution();
System.out.println(sol.generateParenthesis(3));
}
}

public class Solution {

public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
generating(n,n,"",res);
return res;
}

private void generating(int left, int right, String str, List<String> res) {

if(left == 0 && right == 0){
}
if(left > 0){
generating(left-1,right,str+"(",res);
}
if(left<right){
generating(left,right-1,str+")",res);
}
}

public static void main(String[] args){
Solution sol = new Solution();
System.out.println(sol.generateParenthesis(3));
}
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：(Java)LeetCode-22. Generate Parentheses 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)