【蓝桥杯模拟二】括号序列
题目说明:
由 1 对括号,可以组成一种合法括号序列:()。
由 2 对括号,可以组成两种合法括号序列:()()、(())。
由 4 对括号组成的合法括号序列一共有多少种?
分析:
合法括号,必须包含左括号和右括号;这题类似全排列问题;
使用逐步生成法,在上一次获得的合法括号序列的前面和每个左括号后面插入新的括号。
迭代形式代码:
1 private static Set<String> solve(int n) { 2 Set<String> res = new HashSet<>(); 3 4 if (n == 0) { 5 res.add(""); 6 }else if(n==1){ 7 res.add("()"); 8 }else{//n>=2 9 res.add("()");//初始化很重要 10 for (int j = 2; j <= n; j++) { 11 Set<String> res_new = new HashSet<>(); 12 for (String str : res) { 13 for (int i = 0; i < str.length(); i++) { 14 if(str.charAt(i)=='('){ 15 String s=insertInside(str, i);//在左括号里面插入括号 16 res_new.add(s); 17 } 18 } 19 if(!res_new.contains("()"+str)){//在前面插入括号 20 res_new.add("()"+str); 21 } 22 res=res_new; 23 } 24 } 25 } 26 return res; 27 } 28 29 private static String insertInside(String str, int leftIndex) { 30 String left = str.substring(0, leftIndex + 1); 31 String right = str.substring(leftIndex + 1, str.length()); 32 return left + "()" + right; 33 34 }
递归求解:
1 private static Set<String> generaParenthesis(int n) { 2 Set<String> res=new HashSet<String>(); 3 if(n==0){ 4 res.add(""); 5 }else{ 6 Set<String> res_new= generaParenthesis(n-1); 7 for (String str : res_new) {/*在上一个括号序列里遍历*/ 8 for (int i=0;i< str.length();i++) {/*在括号序列里插入新的括号*/ 9 if (str.charAt(i) == '('){ 10 String s=insertInside(str,i); 11 res.add(s); 12 } 13 14 } 15 if (!res.contains("()" + str)) {//在字符串开头插入 16 res.add("()" + str); 17 } 18 } 19 } 20 //在上一次生成的括号序列的前面加(),在左括号后面加去括号 21 22 return res; 23 } 24 25 private static String insertInside(String str, int leftIndex) { 26 String left=str.substring(0, leftIndex+1); 27 String right=str.substring(leftIndex+1,str.length()); 28 29 return left+"()"+right; 30 31 }
持续更新中……
浙公网安备 33010602011771号