-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathsplit-and-merge-array-transformation.py
More file actions
84 lines (77 loc) · 2.38 KB
/
split-and-merge-array-transformation.py
File metadata and controls
84 lines (77 loc) · 2.38 KB
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
# Time: O(n^4 * n!)
# Space: O(n * n!)
# bfs
class Solution(object):
def minSplitMerge(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
def bfs(start, target):
def adj(arr):
for l in xrange(len(arr)):
for r in xrange(l, len(arr)):
sub = arr[l:r+1]
rem = arr[:l]+arr[r+1:]
for i in xrange(len(rem)+1):
if i == l:
continue
yield rem[:i]+sub+rem[i:]
d = 0
if start == target:
return d
lookup = {start}
q = [start]
d += 1
while q:
new_q = []
for u in q:
for v in adj(u):
if v in lookup:
continue
if v == target:
return d
lookup.add(v)
new_q.append(v)
q = new_q
d += 1
return -1
return bfs(tuple(nums1), tuple(nums2))
# Time: O(n^4 * n!)
# Space: O(n * n!)
# bfs
class Solution2(object):
def minSplitMerge(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
def bfs(start, target):
def adj(arr):
for l in xrange(len(arr)):
for r in xrange(l, len(arr)):
sub = arr[l:r+1]
rem = arr[:l]+arr[r+1:]
for i in xrange(len(rem)+1):
if i == l:
continue
yield rem[:i]+sub+rem[i:]
d = 0
lookup = {start}
q = [start]
while q:
new_q = []
for u in q:
if u == target:
return d
for v in adj(u):
if v in lookup:
continue
lookup.add(v)
new_q.append(v)
q = new_q
d += 1
return -1
return bfs(tuple(nums1), tuple(nums2))