3211. Generate Binary Strings Without Adjacent Zeros
Description
You are given a positive integer n
.
A binary string x
is valid if all substrings of x
of length 2 contain at least one "1"
.
Return all valid strings with length n
, in any order.
Example 1:
Input: n = 3
Output: ["010","011","101","110","111"]
Explanation:
The valid strings of length 3 are: "010"
, "011"
, "101"
, "110"
, and "111"
.
Example 2:
Input: n = 1
Output: ["0","1"]
Explanation:
The valid strings of length 1 are: "0"
and "1"
.
Constraints:
1 <= n <= 18
Solutions
Solution 1: DFS
We can enumerate each position \(i\) of a binary string of length \(n\), and for each position \(i\), we can enumerate the possible value \(j\) it can take. If \(j\) is \(0\), then we need to check if its previous position is \(1\). If it is \(1\), we can continue to recurse further; otherwise, it is invalid. If \(j\) is \(1\), then we directly recurse further.
The time complexity is \(O(n \times 2^n)\), where \(n\) is the length of the string. Ignoring the space consumption of the answer array, the space complexity is \(O(n)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|