第七章 遞歸、DFS、剪枝、回溯等問題 ------------- 7.5 “逐步生成結果”之非數值型問題 (合法括號)

題目一:

  輸入括號對數,輸出所有的合法組合,比如輸入1,輸出"()",輸入3,輸出"()()(), (()()), ()(()), (())(), ((()))"。

  思路:比如輸入1,輸出"()",那麼輸入2的話,我們就可以在輸入1的基礎上往左插入一對括號,往右插入一對括號以及把它用括號包含起來。這樣的話左邊和右邊是相同的,我們可以用set集合來去除重複。畫個示意圖如下:

  代碼:

import java.util.HashSet;
import java.util.Set;

public class 合法括號 {

    public static void main(String[] args) {
        Set<String> parenthesis = parenthesis(3);
        System.out.println(parenthesis);
        System.out.println("==============================");
        parenthesis = parenthesis1(3);
        System.out.println(parenthesis);
    }
    
    /* 逐步生成之遞歸解法 */
    public static Set<String> parenthesis(int n) {
        Set<String> s_n = new HashSet<>();
        if (n == 1) {
            s_n.add("()");
            return s_n;
        }
        Set<String> s_n_1 = parenthesis(n - 1);
        for (String eOfN_1 : s_n_1) {
            s_n.add("()" + eOfN_1);
            s_n.add(eOfN_1 + "()");
            s_n.add("(" + eOfN_1 + ")");
        }
        return s_n;
    }

    /* 迭代形式 */
    public static Set<String> parenthesis1(int n) {
        Set<String> res = new HashSet<>(); // 保存上次迭代的狀態
        res.add("()");
        if (n == 1) {
            return res;
        }
        for (int i = 2; i <= n; i++) {
            Set<String> res_new = new HashSet<>();

            for (String e : res) {
                res_new.add(e + "()");
                res_new.add("()" + e);
                res_new.add("(" + e + ")");
            }
            res = res_new;
        }
        return res;
    }

}

  結果:

  注意:這兒的遞歸思路有誤,會漏算。當n=4時,"(())(())"這種情況就打印不出來,不過上面的代碼也算是給我們提供了一種遞歸的思路。下面寫出正確的遞歸思路:   

  解題思路:括號對的合法序列,已經插入的左括號的數目大於等於右括號的數目。
   (1)插入左括號:剩餘的括號中,還有左括號;
   (2)插入右括號:剩餘的括號中,右括號的數目大於左括號的數目;

  代碼及其結果:

public class 合法括號_1 {
    public static void printPar(int l, int r, char[] str, int count) {
        if (l < 0 || r < l)
            return;
        if (l == 0 && r == 0) {
            System.out.println(str);
        } else {
            if (l > 0) {
                str[count] = '(';
                printPar(l - 1, r, str, count + 1);
            }
            if (r > l) {
                str[count] = ')';
                printPar(l, r - 1, str, count + 1);
            }
        }

    }

    public static void main(String[] args) {
        int count = 4;
        char str[] = new char[count * 2];
        printPar(count, count, str, 0);
    }
}

//結果
/*
(((())))
((()()))
((())())
((()))()
(()(()))
(()()())
(()())()
(())(())
(())()()
()((()))
()(()())
()(())()
()()(())
()()()()
*/

題目二:

  判斷一個括號字符串是否合法。

  思路:直接看代碼即可,很容易懂,這裏要注意一下中文括號和英文括號是不同的。

  代碼:

public class Test {

    public static void main(String[] args) {
        System.out.println(chkParenthsis("()a()", 5));
        System.out.println(chkParenthsis("()()", 4));
        System.out.println(chkParenthsis(")())", 4));
        System.out.println(chkParenthsis("(())", 4));
        System.out.println("測試中文括號:"+chkParenthsis("()()", 4));
    }
    
    /**
     * 檢查括號字符串是否合法
     * @param A 源串
     * @param n 源串長度
     * @return
     */
    public static boolean chkParenthsis(String A,int n){
        if(n%2!=0){
            return  false;
        }
        int count = 0;
        for (int i = 0; i < A.length(); i++) {
            if (A.charAt(i) == '('||A.charAt(i) == '(') {  // 避免中文括號
                count++;
            } else if (A.charAt(i) == ')'||A.charAt(i) == ')') {
                count--;
            } else
                return false;
            if (count < 0)
                return false;
        }
        return true;
    }
}

   結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章