首页 > 代码库 > LeetCode Generate Parentheses
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 }
LeetCode Generate Parentheses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。