# (Java)LeetCode-22. Generate Parentheses

178人阅读 评论(0)

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));
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：15064次
• 积分：1055
• 等级：
• 排名：千里之外
• 原创：96篇
• 转载：0篇
• 译文：0篇
• 评论：2条
文章分类
阅读排行
评论排行
最新评论