LeetCode 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:
"((()))", "(()())", "(())()", "()(())", "()()()"
1 public class Solution { 2 String parenthes = "()"; 3 List<String> lastParenthesis=new ArrayList<>(); 4 public List<String> generateParenthesis(int n) { 5 List<String> Parenthesis=new ArrayList<>(); 6 if (n==0) { 7 return lastParenthesis; 8 } 9 lastParenthesis.add(parenthes); 10 if (n==1) { 11 return lastParenthesis; 12 }else { 13 for (int i = 2; i <=n; i++) { 14 for (String eleP : lastParenthesis) { 15 for (int j = 0; j < eleP.length(); j++) { 16 String newone=eleP.substring(0, j+1)+parenthes+eleP.substring(j+1); 17 if (!Parenthesis.contains(newone)) { 18 Parenthesis.add(newone); 19 } 20 } 21 22 } 23 lastParenthesis.clear(); 24 lastParenthesis.addAll(Parenthesis); 25 Parenthesis.clear(); 26 } 27 } 28 return lastParenthesis; 29 } 30 }