[Geeks for Geeks] Generate binary string

Generate binary string

Given a string containing of 0, 1 and ? - a wildcard character, generate all distinct binary strings that can be formed by replacing each wildcard character by either 0 or 1.

  • Time : O(2^n)
  • Space : O(2^n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
void helper(vector<string>& res, string& s, int p) {
if(p == s.length()) res.push_back(s);
else {
if(s[p] == '?') {
s[p] = '0';
helper(res,s,p + 1);
s[p] = '1';
helper(res,s,p + 1);
s[p] = '?';
} else helper(res, s, p + 1);
}
}
public:
vector<string> generate_binary_string(string s) {
vector<string> res;
helper(res, s, 0);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/GeeksforGeeks/generate-binary-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.