-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path446 Arithmetic Slices II - Subsequence.py
70 lines (56 loc) · 1.97 KB
/
446 Arithmetic Slices II - Subsequence.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
#!/usr/bin/python3
"""
A sequence of number is called arithmetic if it consists of at least three
elements and if the difference between any two consecutive elements is the same.
The function should return the number of arithmetic subsequence slices in the
array A. (Subsequence rather than slide)
Author: Rajeev Ranjan
"""
from collections import defaultdict
class Solution:
def numberOfArithmeticSlices(self, A):
"""
Subsequence, count the number, looks like dp
use defaultdict for easy dp array construction
D[i][d] stores the number of arithmetic subsequence ending at A[i], with
delta d
result would be
sum(
D[i][d]
if >= 3 consecutive subsequence A[i], A[j], A[k] ...
for some j, k
)
summing D[j][d] rather than D[i][d] since we need >= 3 subsequence and
D[i][d] contains the length 2.
This approach cannot be extended to >= 4 subsequence
:type A: List[int]
:rtype: int
"""
ret = 0
D = defaultdict(lambda: defaultdict(int))
for i in range(len(A)):
for j in range(i):
d = A[i] - A[j]
D[i][d] += 1 + D[j][d]
if D[j][d] > 0:
# >= 3 subsequence with A[k], A[j], A[i]
ret += D[j][d] # not D[i][d]
return ret
def numberOfArithmeticSlices_error(self, A):
"""
:type A: List[int]
:rtype: int
"""
ret = 0
D = defaultdict(lambda: defaultdict(int))
for i in range(len(A)):
for j in range(i):
delta = A[i] - A[j]
D[i][delta] += 1 + D[j][delta]
for j in range(i):
delta = A[i] - A[j]
if D[j][delta] > 0:
ret += D[i][delta] # counted the length 2
return ret
if __name__ == "__main__":
assert Solution().numberOfArithmeticSlices([2, 4, 6, 8, 10]) == 7