gpt4 book ai didi

Java - 复杂的递归回溯

转载 作者:行者123 更新时间:2023-11-30 03:18:38 25 4
gpt4 key购买 nike

对于 Java 实践,我开始研究一种方法 countBinary,该方法接受整数 n 作为参数,打印所有具有 n 的二进制数按升序排列数字,将每个值打印在单独的行上。假设 n 为非负且大于 0,一些示例输出将类似于 this .

我对此几乎毫无进展。我能够编写一个程序来查找 String 和类似事物的所有可能的字母组合,但我无法使用二进制和整数在这个特定问题上取得几乎任何进展。

显然,解决此问题的最佳方法是定义一个辅助方法,该方法接受与原始方法不同的参数,并构建一组字符作为最终打印的字符串。

重要提示:本练习中我根本不应该使用 for 循环。

编辑 - 重要提示:我需要有尾随 0,以便所有输出的长度相同。

到目前为止,这就是我所拥有的:

public void countBinary(int n)
{
String s = "01";
countBinary(s, "", n);
}
private static void countBinary(String s, String chosen, int length)
{
if (s.length() == 0)
{
System.out.println(chosen);
}
else
{
char c = s.charAt(0);
s = s.substring(1);
chosen += c;
countBinary(s, chosen, length);
if (chosen.length() == length)
{
chosen = chosen.substring(0, chosen.length() - 1);
}
countBinary(s, chosen, length);
s = c + s;
}
}

当我运行代码时,我的输出看起来像 this .

任何人都可以向我解释为什么我的方法没有按照我期望的方式运行,并且如果可能的话,向我展示问题的解决方案,以便我可以获得正确的输出?谢谢!

最佳答案

有更有效的方法可以做到这一点,但这将为您提供一个开始:

public class BinaryPrinter  {
static void printAllBinary(String s, int n) {
if (n == 0) System.out.println(s);
else {
printAllBinary(s + '0', n - 1);
printAllBinary(s + '1', n - 1);
}
}

public static void main(String [] args) {
printAllBinary("", 4);
}
}

我会让你找到更有效的方法。

关于Java - 复杂的递归回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31900710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com