[AlgoExpert] Generate Div Tags

Generate Div Tags

  • Time : O(n!)
  • Space : O(n!)
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
#include <vector>
using namespace std;

const string OPEN = "<div>";
const string CLOSE = "</div>";

void helper(vector<string>& res, int o, int c, int now, string& tmp) {
if(o + c == 0) {
string s;
for(auto& ch : tmp) {
if(ch == '0') s += OPEN;
else s += CLOSE;
}
res.push_back(s);
return;
}
if(o) {
tmp.push_back('0');
helper(res, o - 1, c, now + 1, tmp);
tmp.pop_back();
}
if(c and now) {
tmp.push_back('1');
helper(res, o, c - 1, now - 1, tmp);
tmp.pop_back();
}
}

vector<string> generateDivTags(int n) {
vector<string> res;
string tmp;
helper(res, n, n, 0, tmp);
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/generate-div-tags/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.