简体   繁体   中英

Java - Complex Recursive Backtracking

For Java practice I started working on a method countBinary that accepts an integer n as a parameter that prints all binary numbers that have n digits in ascending order, printing each value on a separate line. Assuming n is non-negative and greater than 0, some example outputs would look like this .

I am getting pretty much nowhere with this. I am able to write a program that finds all possible letter combinations of a String and similar things, but I have been unable to make almost any progress with this specific problem using binary and integers.

Apparently the best way to go about this issue is by defining a helper method that accepts different parameters than the original method and by building up a set of characters as a String for eventual printing.

Important Note: I am NOT supposed to use for loops at all for this exercise.

Edit - Important Note: I need to have trailing 0's so that all outputs are the same length.

So far this is what I have:

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;
    }
}

When I run my code my output looks like this .

Can anyone explain to me why my method is not running the way I expect it to, and if possible show me a solution to my issue so that I might get the correct output? Thank you!

There are more efficient ways to do it, but this will give you a start:

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

I'll let you work out the more efficient way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM