Java - 复杂的递归回溯

Java - Complex Recursive Backtracking

为了 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);
  }
}

我会让你想出更高效的方法。