|
| 1 | +# Time: O(n^2) |
| 2 | +# Space: O(n * d) |
| 3 | + |
| 4 | +# A sequence of numbers is called arithmetic if it consists of at least three elements |
| 5 | +# and if the difference between any two consecutive elements is the same. |
| 6 | +# |
| 7 | +# For example, these are arithmetic sequences: |
| 8 | +# |
| 9 | +# 1, 3, 5, 7, 9 |
| 10 | +# 7, 7, 7, 7 |
| 11 | +# 3, -1, -5, -9 |
| 12 | +# The following sequence is not arithmetic. |
| 13 | +# |
| 14 | +# 1, 1, 2, 5, 7 |
| 15 | +# |
| 16 | +# A zero-indexed array A consisting of N numbers is given. |
| 17 | +# A subsequence slice of that array is any sequence of integers (P0, P1, ..., Pk) |
| 18 | +# such that 0 ≤ P0 < P1 < ... < Pk < N. |
| 19 | +# |
| 20 | +# A subsequence slice (P0, P1, ..., Pk) of array A is called arithmetic |
| 21 | +# if the sequence A[P0], A[P1], ..., A[Pk-1], A[Pk] is arithmetic. In particular, this means that k >= 2. |
| 22 | +# |
| 23 | +# The function should return the number of arithmetic subsequence slices in the array A. |
| 24 | +# |
| 25 | +# The input contains N integers. Every integer is in the range of -2^31 and 2^31-1 and 0 <= N <= 1000. |
| 26 | +# The output is guaranteed to be less than 2^31-1. |
| 27 | +# |
| 28 | +# |
| 29 | +# Example: |
| 30 | +# |
| 31 | +# Input: [2, 4, 6, 8, 10] |
| 32 | +# |
| 33 | +# Output: 7 |
| 34 | +# |
| 35 | +# Explanation: |
| 36 | +# All arithmetic subsequence slices are: |
| 37 | +# [2,4,6] |
| 38 | +# [4,6,8] |
| 39 | +# [6,8,10] |
| 40 | +# [2,4,6,8] |
| 41 | +# [4,6,8,10] |
| 42 | +# [2,4,6,8,10] |
| 43 | +# [2,6,10] |
| 44 | + |
| 45 | +class Solution(object): |
| 46 | + def numberOfArithmeticSlices(self, A): |
| 47 | + """ |
| 48 | + :type A: List[int] |
| 49 | + :rtype: int |
| 50 | + """ |
| 51 | + result = 0 |
| 52 | + dp = [{} for i in xrange(len(A))] |
| 53 | + for i in xrange(1, len(A)): |
| 54 | + for j in xrange(i): |
| 55 | + cnt = dp[j].get(A[i] - A[j], 0) + 1 |
| 56 | + dp[i][A[i] - A[j]] = dp[i].get(A[i] - A[j], 0) + cnt |
| 57 | + result += cnt - 1 |
| 58 | + return result |
0 commit comments