forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-binary-strings-without-adjacent-zeros.cpp
50 lines (47 loc) · 1.18 KB
/
generate-binary-strings-without-adjacent-zeros.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Time: O(n * 2^n)
// Space: O(n)
// backtracking
class Solution {
public:
vector<string> validStrings(int n) {
vector<string> result;
string curr;
const function<void (int)> backtracking = [&](int i) {
if (i == n) {
result.push_back(curr);
return;
}
if (empty(curr) || curr.back() == '1') {
curr.push_back('0');
backtracking(i + 1);
curr.pop_back();
}
curr.push_back('1');
backtracking(i + 1);
curr.pop_back();
};
backtracking(0);
return result;
}
};
// Time: O(n * 2^n)
// Space: O(n * 2^n)
// bfs
class Solution2 {
public:
vector<string> validStrings(int n) {
vector<string> result;
vector<string> q = {""};
for (int _ = 0; _ < n; ++_) {
vector<string> new_q;
for (const auto& x : q) {
if (empty(x) || x.back() == '1') {
new_q.push_back(x + '0');
}
new_q.push_back(x + '1');
}
q = move(new_q);
}
return q;
}
};