Java中括号算法的说明

时间:2018-12-27 14:18:36

标签: java algorithm

我使用以下方法来生成所有有效的括号的打开和关闭组合:

public static void getParentheses(int openParenthesis, int closeParenthesis, String string) {
    if (openParenthesis == 0 && closeParenthesis == 0) {
        System.out.println(string);
    }

    if (openParenthesis > closeParenthesis) {
        return;
    }

    if (openParenthesis > 0) {
        System.out.println("openParenthesis: " + openParenthesis + " / closeParenthesis: " + closeParenthesis);
        getParentheses(openParenthesis - 1, closeParenthesis, string + "(");
    }

    if (closeParenthesis > 0) {
        System.out.println("openParenthesis: " + openParenthesis + " / closeParenthesis: " + closeParenthesis);
        getParentheses(openParenthesis, closeParenthesis - 1, string + ")");
    }
}

然后我在此行中调用此方法:

getParentheses(3, 3, "");

输出为:

openParenthesis: 3 / closeParenthesis: 3
openParenthesis: 2 / closeParenthesis: 3
openParenthesis: 1 / closeParenthesis: 3
openParenthesis: 0 / closeParenthesis: 3
openParenthesis: 0 / closeParenthesis: 2
openParenthesis: 0 / closeParenthesis: 1
((()))
openParenthesis: 1 / closeParenthesis: 3 //Line8
openParenthesis: 1 / closeParenthesis: 2
openParenthesis: 0 / closeParenthesis: 2
openParenthesis: 0 / closeParenthesis: 1
(()())

我不明白为什么在Line8处,openParenthesis的值为1,因为该方法的最后一次调用是使用0和{{1 }}?是什么使它增加到0

1 个答案:

答案 0 :(得分:0)

第3行和第8行来自同一函数调用: 第3行是由

产生的
if (openParenthesis > 0) {
    System.out.println("openParenthesis: " + openParenthesis + " / closeParenthesis: " + closeParenthesis);
    getParentheses(openParenthesis - 1, closeParenthesis, string + "(");
}

第8行:

if (closeParenthesis > 0) {
    System.out.println("openParenthesis: " + openParenthesis + " / closeParenthesis: " + closeParenthesis);
    getParentheses(openParenthesis, closeParenthesis - 1, string + ")");
}

从递归调用返回后。