forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
count-paths-that-can-form-a-palindrome-in-a-tree.cpp
72 lines (70 loc) · 2.12 KB
/
count-paths-that-can-form-a-palindrome-in-a-tree.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Time: O(n)
// Space: O(n)
// iterative dfs, freq table
class Solution {
public:
long long countPalindromePaths(vector<int>& parent, string s) {
unordered_map<int, int> cnt;
cnt[0] = 1;
vector<vector<int>> adj(size(parent));
for (int u = 0; u < size(parent); ++u) {
if (parent[u] != -1) {
adj[parent[u]].emplace_back(u);
}
}
const auto& iter_dfs = [&]() {
int64_t result = 0;
vector<pair<int, int>> stk = {{0, 0}};
while (!empty(stk)) {
auto [u, mask] = stk.back(); stk.pop_back();
if (u) {
mask ^= 1 << (s[u] - 'a');
for (int i = 0; i < 26; ++i) {
if (cnt.count(mask ^ (1 << i))) {
result += cnt[mask ^ (1 << i)];
}
}
result += cnt[mask]++;
}
for (const auto& v : adj[u]) {
stk.emplace_back(v, mask);
}
}
return result;
};
return iter_dfs();
}
};
// Time: O(n)
// Space: O(n)
// dfs, freq table
class Solution2 {
public:
long long countPalindromePaths(vector<int>& parent, string s) {
unordered_map<int, int> cnt;
cnt[0] = 1;
vector<vector<int>> adj(size(parent));
for (int u = 0; u < size(parent); ++u) {
if (parent[u] != -1) {
adj[parent[u]].emplace_back(u);
}
}
const function<int64_t (int, int)> dfs = [&](int u, int mask) {
int64_t result = 0;
if (u) {
mask ^= 1 << (s[u] - 'a');
for (int i = 0; i < 26; ++i) {
if (cnt.count(mask ^ (1 << i))) {
result += cnt[mask ^ (1 << i)];
}
}
result += cnt[mask]++;
}
for (const auto& v : adj[u]) {
result += dfs(v, mask);
}
return result;
};
return dfs(0, 0);
}
};