forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-unequal-adjacent-groups-subsequence-ii.py
86 lines (72 loc) · 2.35 KB
/
longest-unequal-adjacent-groups-subsequence-ii.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# Time: O(n^2)
# Space: O(n)
import itertools
# dp, backtracing
class Solution(object):
def getWordsInLongestSubsequence(self, n, words, groups):
"""
:type n: int
:type words: List[str]
:type groups: List[int]
:rtype: List[str]
"""
def check(s1, s2):
return len(s1) == len(s2) and sum(a != b for a, b in itertools.izip(s1, s2)) == 1
dp = [[1, -1] for _ in xrange(n)]
for i in reversed(xrange(n)):
for j in xrange(i+1, n):
if groups[i] != groups[j] and check(words[j], words[i]):
dp[i] = max(dp[i], [dp[j][0]+1, j])
result = []
i = max(xrange(n), key=lambda x: dp[x])
while i != -1:
result.append(words[i])
i = dp[i][1]
return result
# Time: O(n^2)
# Space: O(n)
import itertools
# dp, backtracing
class Solution2(object):
def getWordsInLongestSubsequence(self, n, words, groups):
"""
:type n: int
:type words: List[str]
:type groups: List[int]
:rtype: List[str]
"""
def check(s1, s2):
return len(s1) == len(s2) and sum(a != b for a, b in itertools.izip(s1, s2)) == 1
dp = [[1, -1] for _ in xrange(n)]
for i in xrange(n):
for j in xrange(i):
if groups[i] != groups[j] and check(words[j], words[i]):
dp[i] = max(dp[i], [dp[j][0]+1, j])
result = []
i = max(xrange(n), key=lambda x: dp[x])
while i != -1:
result.append(words[i])
i = dp[i][1]
result.reverse()
return result
# Time: O(n^2)
# Space: O(n^2)
import itertools
# lis dp
class Solution3(object):
def getWordsInLongestSubsequence(self, n, words, groups):
"""
:type n: int
:type words: List[str]
:type groups: List[int]
:rtype: List[str]
"""
def check(s1, s2):
return len(s1) == len(s2) and sum(a != b for a, b in itertools.izip(s1, s2)) == 1
dp = [[] for _ in xrange(n)]
for i in xrange(n):
for j in xrange(i):
if groups[i] != groups[j] and check(words[j], words[i]) and len(dp[j]) > len(dp[i]):
dp[i] = dp[j]
dp[i] = dp[i]+[i]
return map(lambda x: words[x], max(dp, key=lambda x: len(x)))