[LeetCode] Generate Binary Strings Without Adjacent Zeros

3211. Generate Binary Strings Without Adjacent Zeros

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.

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
class Solution {
void helper(vector<string>& res, string& s, int n) {
if(s.length() == n) {
res.push_back(s);
} else {
s.push_back('1');
helper(res,s,n);
s.pop_back();
if(s.back() == '1') {
s.push_back('0');
helper(res,s,n);
s.pop_back();
}
}
}
public:
vector<string> validStrings(int n) {
if(n == 1) return {"0","1"};
vector<string> res;
string s0 = "0", s1 = "1";
helper(res,s0,n);
helper(res,s1,n);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/07/07/PS/LeetCode/generate-binary-strings-without-adjacent-zeros/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.