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.py
64 lines (55 loc) · 1.69 KB
/
count-paths-that-can-form-a-palindrome-in-a-tree.py
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
# Time: O(n)
# Space: O(n)
import collections
# iterative dfs, freq table
class Solution(object):
def countPalindromePaths(self, parent, s):
"""
:type parent: List[int]
:type s: str
:rtype: int
"""
def iter_dfs():
result = 0
cnt = collections.defaultdict(int)
cnt[0] = 1
stk = [(0, 0)]
while stk:
u, mask = stk.pop()
if u:
mask ^= 1<<(ord(s[u])-ord('a'))
result += cnt[mask]+sum(cnt[mask^(1<<i)] if mask^(1<<i) in cnt else 0 for i in xrange(26))
cnt[mask] += 1
for v in reversed(adj[u]):
stk.append((v, mask))
return result
adj = [[] for _ in xrange(len(parent))]
for u, p in enumerate(parent):
if p != -1:
adj[p].append(u)
return iter_dfs()
# Time: O(n)
# Space: O(n)
import collections
# dfs, freq table
class Solution2(object):
def countPalindromePaths(self, parent, s):
"""
:type parent: List[int]
:type s: str
:rtype: int
"""
def dfs(u, mask):
result = 0
if u:
mask ^= 1<<(ord(s[u])-ord('a'))
result += cnt[mask]+sum(cnt[mask^(1<<i)] if mask^(1<<i) in cnt else 0 for i in xrange(26))
cnt[mask] += 1
return result+sum(dfs(v, mask) for v in adj[u])
adj = [[] for _ in xrange(len(parent))]
for u, p in enumerate(parent):
if p != -1:
adj[p].append(u)
cnt = collections.defaultdict(int)
cnt[0] = 1
return dfs(0, 0)