-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path132.py
More file actions
71 lines (56 loc) · 2.15 KB
/
132.py
File metadata and controls
71 lines (56 loc) · 2.15 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
class Solution(object):
def find132pattern(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
# Attemp 1 - Brute Force Solution - Time limit exceeded
n = len(nums)
i = 0
while i < n:
j = i + 1
while j < n:
k = j + 1
while k < n:
if i < j < k and nums[i] < nums[k] < nums[j]:
return True
k += 1
j += 1
i += 1
return False
class Solution:
def find132pattern(self, nums: List[int]) -> bool:
# Logic 1: problem statement but contigously (Q wants without being cont and just i<j<k)
"""
for i in range(1, len(nums)-1):
if nums[i-1] < nums[i+1] < nums[i]:
return True
return False
"""
# Logic 2: same as above but without being contiguous/adjacent
def backtrack(current, nums):
print(current, nums)
if len(current) >= 3:
#print(current)
return True
for i in range(len(nums)):
if i+1 >= len(nums):
nxt = []
else:
nxt = nums[i+1:]
if len(current) == 0:
if nums[i] not in self.start_points:
if backtrack(current + [nums[i]], nxt):
return True
self.start_points.add(nums[i])
elif len(current) == 1 and current[-1] < nums[i]:
if current[0] + nums[i] not in self.second_points:
if backtrack(current + [nums[i]], nxt):
return True
self.second_points.add(current[0] + nums[i])
elif len(current) == 2 and current[0] < nums[i] < current[1]:
return True
return False
self.start_points = set()
self.second_points = set()
return backtrack([], nums)