1. 程式人生 > 實用技巧 >【藍橋杯模擬二】括號序列

【藍橋杯模擬二】括號序列

題目說明:

由 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     }
遞迴形式生成括號

持續更新中……