Binary Strings Without Two 1s in a Row

Problem

Read n. Print all binary strings of length n that do not contain two 1s next to each other, one per line, in ascending order.

Constraints

  • 1 <= n <= 12

Examples

Input

3

Output

000
001
010
100
101

Solutions

Best approachTime O(F(n) * n)Space O(n)

The rule is checked while building, so invalid strings are never created. The number of valid strings of length n follows the Fibonacci numbers.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process a number.
 * Input   : One integer n.
 * Output  : The strings.
 * Approach: Backtracking with a rule.
 * Time    : O(F(n) * n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
        // Step 1: Build the string character by character. A 1 is allowed only if the previous character is not 1.
        static void build(String current, int length, java.util.List<String> result) {
            // Step 2: Base case. The string is complete: save it.
            if (current.length() == length) {
                result.add(current);
                return;
            }

            // Step 3: A 0 is always allowed. We try 0 first, so the result is in ascending order.
            build(current + "0", length, result);

            // Step 4: A 1 is allowed only if the string does not end with 1.
            if (current.isEmpty() || current.charAt(current.length() - 1) != '1') {
                build(current + "1", length, result);
            }
        }

    // This method solves the task. It receives the input and returns the answer.
    static String[] solve(long n) {
        java.util.List<String> result = new java.util.ArrayList<>();
        build("", (int) n, result);
        return result.toArray(new String[0]);
    }

    public static void main(String[] args) {
        long n = new Scanner(System.in).nextLong();
        System.out.println(String.join("\n", solve(n)));
    }
}
Hints (1)
  1. How is this related to the Fibonacci numbers?