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

leetcode--22. 括号生成

2018-04-08 14:29:58

<LeetCode>22. 括号生成

2018-04-19 10:52:02

leetcode22

2015-10-06 22:34:53

LeetCode 22 Generate Parentheses（生成括号）

2015-11-10 22:41:54

leetCode 22.Generate Parentheses (生成括号) 解题思路和方法

2015-07-06 22:11:08

leetcode-22 有效的括号

2018-05-16 14:27:06

leetcode--22--产生有效括号

2016-10-03 12:54:19

leetcode 22 -- Generate Parentheses

2015-06-06 23:23:08

leetcode-java-22. Generate Parentheses

2016-06-09 21:28:09

LeetCode22GenerateParentheses--In Java

2016-02-21 19:32:58