java - 回溯递归问题来解决平衡括号

标签 java recursion backtracking parentheses

我需要了解如何从递归函数回溯。我知道阶乘或斐波那契等基本函数是如何完成的。我不明白这个问题。

我尝试消除第二个递归调用中的其他条件,但它会生成所有可能的括号集,包括不平衡的括号集。

public final class Example {
    public static void parentheses(int left, int right, String str) {
        if (left == 0 && right == 0) {
            System.out.print(str);
            System.out.print(", ");
        }

        if (left > 0) {
            str += "(";
            parentheses(left - 1, right, str);
        }

        if (right > 0 && right > left) {
            str += ")";
            parentheses(left, right - 1, str);
        }
    }

    public static void main(String[] args) {
        parentheses(3, 3, "");
    }
}

我希望结果是所有可能的平衡括号集但是在每次递归调用之后我都会得到 1 个额外的左括号。预期输出是:

((())), (()()), (())(), ()(()), ()()(),

我得到的输出是:

((())), ((()()), ((()()(), (()(()), (()(()(),

最佳答案

问题出在下面。

 str += "(";

您每次都会创建一个新的字符串对象并在递归调用中传递它。因此,每个递归调用的字符串对象都有不同的值,因此您预期的递归会失败。 Java 中的字符串是不可变的。

将代码更改为以下内容:

        public static void parentheses(int left, int right, String str) {

        if ( right==0 && left==0) {
            System.out.print(str);
            System.out.print(", ");

        }
        if (left > 0) {
            parentheses(left-1, right, str +"(" ); // New object will be created but its value will be dereferenced from the old one and attached to the new one.
            // As a result all our manipulation of string we did will be saved.
        }
        if ( right >0 && right > left) {
            parentheses(left, right - 1, str +")" );
        }
    }

输入:

parentheses(3,3,""); // Function call

输出:

((())), (()()), (())(), ()(()), ()()(),

关于java - 回溯递归问题来解决平衡括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56480795/

相关文章:

ruby - 算法回溯 : How to do recursion without storing state

java - 带回溯的数独算法不返回任何解

java - 尝试将 2 个数组传递给方法并使用这 2 个数组中的值打印出一个表

java - 只想创建一次对象

c - 恢复 C (gcc) 中的递归函数?

java - 无法使用返回函数终止递归

java - 尽管使用 indexInBounds 仍获取 ArrayIndexOutOfBounds

list - SWI-Prolog : How to stop the predicate when the list is empty?(包括谓词)

java - java中的设计模式

Java AWS SDK 2.x 异步客户端 - 无法覆盖线程池执行器