If you don't care about speed and memory, you recursively use cold, which leads to a small and short solution:
public static void print01PermutationsUpToLength(final String currentString, final int upTo) { if (upTo == 0) { System.out.println(currentString); return; } print01PermutationsUpToLength(currentString + "0", upTo - 1); print01PermutationsUpToLength(currentString + "1", upTo - 1); }
(java. Obviously, this can be done in every language that allows recursion and call by value or a copy of String)
If you don't like the String argument, you can add a launch function:
public static void print01PermutationsUpToLength(final int upTo) { print01PermutationsUpToLength("", upTo); }
results:
final int upToLength = 3; print01PermutationsUpToLength(upToLength); 000 001 010 011 100 101 110 111
The formatting can be changed the way you want, it was just to better see the results.
You can change the order if you switch parts of the string structure ( currentString + "0" ).
source share